question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
7,743,775 | 7,743,820 | Virtual keyword makes inaccessible a method from the derived objects | I have this code:
#include <iostream>
class Super{
public:
virtual void showName();
};
class Special1 : public Super {
public:
void showName();
void sayHello();
};
class Special2 : public Super {
public:
void showName();
void sayGoodbye();
};
void Super::showName() {
std::cout << "I'm super!... | The output is closer to correct with virtual and incorrect with it (unless you really wanted that). The cast doesn't change the type of the objects, just the type of the pointers. They are still of type Super, and so it's Super::showName that should run.
Casting one pointer type to another pointer type doesn't change t... |
7,743,818 | 7,744,157 | Does the android NDK compiler support inline assembly? (ie asm or __asm keywords?) | Just wondering if andorid NDK supports direct embedding of asm?
asm{
//lots of strange asm instructions...
}
If so, I presume you'd have to get some refference to the instruction sets of the specfic arm achitecture - where would you find these?
Thanks,
Steve.
| The Android NDK uses GCC, so you can safely look at GCC documentation.
As for the specific ARM instructions, something like ARM architecture may be a good starting point.
|
7,743,821 | 7,746,682 | gluLookAt and glFrustum with a moving object | Original Question/Code
I am fine tuning the rendering for a 3D object and attempting to implement a camera following the object using gluLookAt because the object's center y position constantly increases once it reaches it's maximum height. Below is the section of code where I setup the ModelView and Projection matrice... | The answer by Nicol Bolas pretty much tells what you're doing wrong so I'll skip that. You are looking for an solution rather than telling you what is wrong, so let's step right into it.
This is code I use for projection matrix:
glViewport(0, 0, mySize.x, mySize.y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPer... |
7,744,034 | 7,853,294 | Boost Http Server Example Crashes at boost::thread on Ubuntu 10.10 | I'm trying to compile and run the following example on Ubuntu 10.10
http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/example/http/server3/
but it crashes at:
// Create a pool of threads to run all of the io_services.
std::vector<boost::shared_ptr<boost::thread> > threads;
for (std::size_t i = 0; i < thread_poo... | It seems ildjarn's initial guess might be correct.
I found there are two versions of the boost lib on my Ubuntu 10.10. I removed them thoroughly, and installed the latest one, and the issue was gone.
|
7,744,314 | 7,744,792 | Access Exchange Mails using EWS without C# code? | Is there a way I can access the Exchange Mails/Calendars/Addressbook without .NET or non cross platform thing? I want to access them with C++ but on both MS and Linux. Their docs says it is possible but there is no any non C#/.Net example.
EWS combines the functionality that is included in WebDAV and CDOEX, and provide... | I agree that there are few examples outside the C# / Powershell realm. That being said, if you stick to plain EWS, it should be possible. I have no idea the WebServce access from C++ is anything similar to C#. In C# you point Visual Studio (or wsdl.exe) to the WSDL of the WebService and it will create a set of proxy cl... |
7,744,441 | 8,127,145 | Using Boost statechart, how can I transition to a state unconditionally? | I have a state A that I would like to transition to its next state B unconditionally, once the constructor of A has completed. Is this possible?
I tried posting an event from the constructor, which does not work, even though it compiles. Thanks.
Edit: Here is what I've tried so far:
struct A : sc::simple_state< A, Acti... | I've updated my OP with my solution, here it is so I can close the question.
The problem is that you cannot inherit from simple_state to achieve the desired transition, you must inherit from state, which then requires that you modify the constructor accordingly.
struct A : sc::state< A, Active >
{
public:
t... |
7,744,508 | 7,747,233 | retrieving the results of a reentrant lexing without file i/o | I have a flex module in a C++ project that I want to call from multiple threads.
My .lex file's options include stack and reentrant.
Assuming that it is possible to call yylex on different scanner objects from different threads simultaneously and not have one lexing sequence block the other (which I think is the case b... | Well, if you're using the default output, it goes to a FILE, but there's no need to do that --you can just write your actions to send the output to anywhere you want. You can define your own YY_EXTRA_TYPE data structure and use yyget_extra/yyset_extra to manipulate it, if you need some extra per-scanner state to keep ... |
7,744,710 | 7,753,636 | Design Pattern, Multi agent system, Robotics | A short description:
There is 5 robots, and each robot runs a program named "Planner".
Each robot has a post, and they must do a task(select it from many tasks) according to that post. the main loop is (Pseudo code):
while(true)
{
/*1*/ WorldModel::getSingelton()->update();
/*2*/ Post post = selectAPost();
/*3... | Yes, there is a lot! Three examples of academic works on design patterns for multiagent design:
L. Sabatucci, M. Cossentino, S. Gaglio. A Semantic Description For Agent Design Patterns. In Proc. of the Sixth International Workshop "From Agent Theory to Agent Implementation" (AT2AI-6) at The Seventh International Joint ... |
7,744,737 | 7,744,757 | ellipsis try catch on c++ | Can an ellipsis try-catch be used to catch all the errors that can lead to a crash? Are there are any anomalies?
try
{
//some operation
}
catch(...)
{
}
| No, it'll only catch C++ exceptions, not things like a segfault, SIGINT etc.
You need to read up about and understand the difference between C++ exceptions and for want of a better word, "C-style" signals (such as SIGINT).
|
7,744,975 | 7,745,369 | Why do C# and VB.NET implicitly marshal char* differently? | So I have a function, written in C++, that looks like this...
extern "C" __declspec(dllexport) int __stdcall SomeFunction(char *theData)
{
// stuff
}
... and I'm using it in my current project (written in C#). There are other projects that use this function written in VB, looking like this:
Public Declare Function... |
Now I know that VB.NET and C# are quite different, but I suppose I always assumed that strings were strings
Strings are immutable in .net. Ask yourself why it is that ByVal passing of an immutable data type can result in the value changing. That doesn't happen for normal functions, just for Declare.
I'd guess it all... |
7,745,076 | 14,719,008 | VC++ Resource Compiler (RC) option /n ...? | I was just reading the description of the available command line options for the resource compiler that ships with VC++ 2010 (rc.exe), and one of them caught my attention:
/n : Append null's to all strings in the string tables
Maybe the answer is obvious and I'm just not thinking down the right path, but when would thi... | The strings in the STRINGTABLE are not usually terminated by zero terminator, instead the format of STRINGTABLE specifies each string is preceded with string length. Normally LoadString() copies the string resource into an application-provided buffer and appends the zero-terminator. In that case you actually do not nee... |
7,745,099 | 7,745,826 | Design Pattern for multithreaded task overall progress report | I have a library with an IJobMaker entity that creates a certain amount of IJob objects to be run on threads of their own managed by the user.
To track each IJob's progress I implement the observer pattern with an IProgressObserver within every job. The difficulty arises when I wish to report on OVERALL progress.
The i... | First of all, it's quite bad practice to use floats in such cases. Use an integer.
There is another suggestion. You can use segmentation - synchronise only few threads by one mutex/atomic (one segment). And then collect total among all segments.
Also, there is good place to start looking around highly parallel algorith... |
7,745,405 | 7,745,470 | Accessing X and Y in template class A like in template<template<int X, int Y> class> class A; | What is the correct syntax to use template parameters of a template class argument in another template class?
For example: How can I access X and Y of class Param in class Foo?
Program:
template < template < int, int > class X1>
struct Foo {
int foo() {
printf("ok%d %d\n", X1::X, X1::Y);
return 0;
}};
template < int ... | You can't. The template template parameter means that you take a template name without supplied template arguments.
Foo< Param > tt;
Here you can see that no values are supplied for Param. You'd take a template template parameter so that Foo itself could instantiate Params with any arguments it likes.
Example:
templat... |
7,745,434 | 7,745,474 | runtime type conversion in C++, how? | I am trying to analyze a geotiff file, very simple, just trying to get all the tag information. I know there are libs available such as libtiff and libgeotiff. What I want to do is simple: read out all the tags.
The tag structure is:
struct ifd_entry
{
_int16 tag_id;
_int16 field_type;
_int16 field_count;
_int16 field_... | If the number of types is fixed and short, I would use Boost.Variant. Having a variant over the possible types, then the visitor pattern can be applied to for instance print the fields. The internal implementation may not be too different from what you are currently doing, but I find it more idiomatic.
|
7,745,630 | 7,745,666 | Is possible to use template argument as string? | I want to use passed template parameter as string. Is it possible?
T is class, what do i need to change to get that code work?
void registerClass(const std::string &name, Handler *handler);
template<class T>
void registerClass() {
registerClass( "get T as string", new DefaultHandler<T>());
}
| The closest you can get to get a type as a string is with typeid( T )->name(). However, there is no standarization for type names, so you can't trust in getting a valid name from it. A standard compliant implementation may very well return empty strings for all type names.
|
7,745,684 | 7,745,739 | Automatic template class generation at compile time in C++ | I have a class, called DynamicTexture that takes in the width and height of a texture as template parameters. The parameters are used to instantiate a fixed size table (which is also a template class).
In my case, I am instantiating the DynamicTexture for various powers of two width/height (so 2x2, 4x4, 8x8, 16x16, 32... |
Now the question is, can I automate that process somehow?
You can do it with some advanced metaprogramming tricks:
template< int Width, int Height >
struct textures_holder
: textures_holder< Width * 2, Height * 2 >
{
typedef textures_holder< Width * 2, Height * 2 > base_t;
void show( int currTexSize ) co... |
7,745,731 | 7,746,072 | Using empty Boost accumulators | I am curious, what average is obtained from this code snippet? The accumulator is intended to be empty.
boost::accumulators::accumulator_set<
int,
boost::accumulators::features<boost::accumulators::tag::mean>
> Accumulator;
int Mean = boost::accumulators::mean(Accumulator);
The average is non-zero when I test... | Any value would be a valid mean for an empty set of values. That is x * 0 = 0 holds for any x.
You could add a count feature to your accumulator_set and query it to see if its 0.
|
7,745,948 | 7,745,984 | Multiple inheritance design implementation | I have 3 classes, A, B, and C where B is an A and C is an A.
These classes are designed to retain history, so A provides a virtual method that derived classes can create to be notified when the history should be archived, called void archive().
Now suddenly there is a need to have the information from A, B, and C in a ... | Your approach is the standard one. C++ has multiple-inheritance, and you should feel free to use it. It looks like you know how to do it correctly.
|
7,746,044 | 7,763,503 | Using SQLite with WinRT | I am developing a metro ui application and I would like to use SQLite for some internal data instead of JET in order to take advantage of some already-written code.
Howerver when I try to use sqlite3_open for opening a data base, it does not work. I get an error saying a cannot open the data base.
I believe some APIs u... | This code should work:
auto localAppDataParh = Windows::Storage::ApplicationData::Current->LocalFolder->Path;
std::wstring path( localAppDataParh->Data() );
path += L"\\sample.db";
sqlite3* db;
int rc = sqlite3_open16( path.c_str(), &db);
I believe some APIs used by the SQLite cannot be used on metro style applicatio... |
7,746,056 | 7,746,329 | Matrix math with cosin / sin | I have a routine which will accept the joint parameters d, theta, a, and alpha as input and will produce the corresponding 4x4 homogeneous matrix as output. I have tested my matrix multiplication and it does work fine. I will get 5 matrices from the input which will all be multiplied together resulting in $t^0_5$ . The... | A couple of problems, one is in the code you showed, the other is not.
Problem 1: This may not the source of your problem, but double pi = 3.14159; is fine for floats, but is not for doubles. You should have pi to at least 16 places there. Better yet, use M_PI from <math.h>, a common extension in many compilers. If you... |
7,746,273 | 7,746,610 | Packaging Predicate Functors | I'm wondering about conventions and best practices regarding the packaging of predicate functors. For example, given a class like:
class Timer
{
public:
Timer(const std::string& name, int interval);
bool nameIs(const std::string& name) const;
private:
std::string name_;
int interval_;
};
that is (in one case)... | This is open to debate. I prefer to create a nested class. This way a functor that is intended only to work with a particular type of object is namespace-scoped within that object.
I also generally name the predicate match_xxx where xxx is the parameter I'm matching on.
To wit:
class Timer
{
// ...
public:
clas... |
7,746,461 | 7,746,499 | How can I see how a C++ class gets laid out in memory with gdb? | I've got a debug build of a program (the V8 JavaScript VM) and I want to understand how instances of certain classes are laid out in memory. I can pretty-print structures like this:
(gdb) print thread_local
$6 = {
blocks_ = {
data_ = 0x868ceb0,
capacity_ = 7,
length_ = 1
},
entered_contexts_ = {
... | You can always print out the address of each member and this to figure it out yourself (you use & to get the member address, just like in the language itself).
|
7,746,594 | 7,891,661 | MFC CListCtrl eating mouse up events? | It seems that CListCtrl doesn't send mouse up events unless there is a double click.
I've attempted sending the missing message from the mouse down handlers to compensate but that causes other undesirable behavior. Then I thought I could send the message within the mouse move handler to be a bit more accurate by checki... | For reference here's what I have that works but it's a shameful hack. If no one can come up with anything better than this that's really sad.
Header:
#pragma once
// CListCtrlEx
class CListCtrlEx : public CListCtrl
{
DECLARE_DYNAMIC(CListCtrlEx)
public:
CListCtrlEx();
virtual ~CListCtrlEx();
bool IsS... |
7,746,630 | 7,746,904 | Progress Indicator for Multiple downloads with cURLpp | I am writing a program that downloads multiple files (at the moment its only 2). I am trying to get it to display a progress bar for each download using the ProgressFunction callback. The problem I am running into is I cannot figure out a way to differentiate between the progress between the two files. Right now it is ... | Disclaimer: My C++ is rusty, and I have never used curlpp before, so the code below may need a bit of massaging.
What you need in your callback function is something that can differentiate between the two downloads. Since curlpp doesn't give you that, you probably need to use a functor instead. So, for your progress ca... |
7,746,648 | 7,746,745 | Throwing the fattest people off of an overloaded airplane. | Let's say you've got an airplane, and it is low on fuel. Unless the plane drops 3000 pounds of passenger weight, it will not be able to reach the next airport. To save the maximum number of lives, we would like to throw the heaviest people off of the plane first.
And oh yeah, there are millions of people on the air... | One way would be to use a min heap (std::priority_queue in C++). Here's how you'd do it, assuming you had a MinHeap class. (Yes, my example is in C#. I think you get the idea.)
int targetTotal = 3000;
int totalWeight = 0;
// this creates an empty heap!
var myHeap = new MinHeap<Passenger>(/* need comparer here to order... |
7,746,738 | 7,748,073 | First chance exception at 0x5919c8ec (msvcr100d.dll): 0xC0000005: Access violation reading location 0xfeeefeee | I'm having this error while comparing two strings (using an overloaded operator).
The error happens here :
void addEtu(node *Node, element *Etu){
if (Node->Value == NULL)
Node->Value = Etu;
else{
if (Node->left == NULL && *Node > *Etu) //This line specifically
Node->left->Value = Etu... | It looks like you are storing Etu in the tree, but after you exit addEtu, you are deleting Etu. This means the node in the tree is now pointing to a deleted object.
|
7,746,849 | 7,746,929 | C++ : const references and initialization order | I am wondering if I am using the good approach in the following :
I want to construct a parent class (class A), this class should own an instance of a given "Foo" class
I want the parent class to own a child class member (class B) and this member should have a reference to the foo member of the parent class.
The code... | No, this is broken. Your mB will hold a reference to whatever you passed to the constructor of the A object, not to mFoo. Instead, you should say:
A(const Foo & foo) : mFoo(foo), mB(mFoo) { }
Note that mB is a copy of the constructor argument, and not a reference, so your MyTest function is fine.
|
7,747,008 | 7,747,117 | SDL_GetTicks()-based movement? | I'm writing a game of pong in OpenGL and SDL. I have a small knowledge of how SDL_GetTicks() works but I am struggling to think of a way to implement how to make my ball move for example every 1000 milliseconds being the novice I am.
Short examples, explanations, help, anything at all would be appreciated greatly.
| Ye Olde Fix Your Timestep!
You don't have to use RK4, the "interpolate between the last two sim states" is the important part.
|
7,747,069 | 7,747,129 | Where can I find the C++11 standard papers? |
Possible Duplicate:
Where do I find the current C or C++ standard documents?
Where can I find the full C++11 standard? I know features of it are floating around the internet but I can't seem to find the document itself.
| You can get the full, final standard directly from the ISO, or some national bodies.
You probably don't want to get in a hurry though. The ANSI (for one) normally re-publishes an official version with identical technical material -- basically the only change is saying "ANSI/ISO" on the the title page instead of just "I... |
7,747,092 | 7,747,111 | bitset or native data types with bitwise operations for bitmap? | I would like to implement bitmaps of 64 bits, 128 bits and 256 bits. I was thinking of using specialized classes for these three. I need to set the bits and also look them up. The bitset will not be dynamic, static implementations of 64, 128 and 256 bits will be used.
What are the pros and cons of using the c++ bitse... | Well, definitely there is some overhead in standard bitsets. Your implementation is going to be faster (but you need to invest some effort in coding it and making it efficient and bug-free).
I would however use standard bitsets and not fight against that overhead until this is a proven bottleneck. You know the often ci... |
7,747,106 | 7,747,215 | Window without client area in WinAPI | On these screenshots we can see unordinary window frame in different applications:
QIP logo on its login window frame (not client area) - http://postimage.org/image/2fdjg0h44/
Buttons (back/next) and address field on the Windows 7 explorer window frame - http://postimage.org/image/2fdrpp7l0/
In Google Chrome tabs take... | You are looking to resize the nonclient area of the form: Controls and the Desktop Window Manager
|
7,747,223 | 7,747,292 | Thread-Safe Concurrent call to external command in c++ | I've been looking around on the internet trying to find a way to make concurrent calls to an external program in a thread safe manner from within my C++ program.
As far as I've understood, popen, system and fork are not thread safe.
It seems to me that there is something missing here, that I haven't been able to find s... | What makes you think that popen, system and fork are thread-unsafe? A quote from the man page on fork:
The child process is created with a single thread — the one that
called fork(). The entire virtual address space of the parent is
replicated in the child, including the states of mutexes,
condition v... |
7,747,556 | 7,750,236 | Native Java / Python / Objective C in Firefox? | Is it possible to integrate Java, Python, or Objective C directly with the Firefox browser? In particular to do "real", native tasks such as writing files or connecting to a local database, or better yet, directly calling systems level code ?
Notably, there is a post on native code execution, somewhat slanted toward... |
In particular to do "real", native tasks such as writing files or
connecting to a local database, or better yet, directly calling
systems level code ?
You don't need an extra language for that, Firefox extensions can do it already:
Writing files
Connecting to a local SQLite database
Calling system libraries dire... |
7,747,591 | 7,747,751 | Can i Write to Embedded Resource Text File? | im stucking with Writing to Text File in the Resource, i can read from
the specified file, but cant write, its says Stream is not writeable.
there is any way to fix it ? i do it for my program builder, thanks in advice!
| You can not write the the application bundle, pick another location, perhaps the Documents directory on iOS or the Application Support directory in OSX.
On iOS the resource bundle is also signed, another reason writing to it is not allowed.
|
7,747,683 | 7,748,152 | Relative mouse position of SDL_Surface | In my application I need to return the relative mouse position from an SDL_Surface, the problem is the mouse position that gets returned is relative to the SDL window and not the SDL_Surface. I guess my question is what is the easiest / most effective way of doing this. Any questions just ask. Thanks.
EDIT: Sorry I sho... | Just add(or subtract, depending on how you look at it) the offset to the mouse coordinates. So you're drawing the surface something like this:
SDL_Rect dest_rect = { -camera.x, -camera.y };
SDL_BlitSurface(image_surface, NULL, screen_surface, &dest_rect);
I don't know if you're using event based mouse handling, or if... |
7,747,843 | 7,747,880 | C++ Deleting part of dynamic array | Say I have a dynamic array like:
int* integers = new int[100];
Is there a way to delete only part of the array such as:
int* integers2 = integers + 50;
delete[] integers2;
I want to not only delete everything 50 and beyond, but if I call another delete[] on the original integers array, then it would only delete the c... | No, this will not behave correctly. You can only delete[] pointers that you got from new[], else the results are undefined and bad things might happen.
If you really need the array to get smaller you have to allocate a new one and copy the contents manually.
|
7,747,844 | 7,748,016 | Game of Pig function repeating? | For homework we are suppose to progrma a pig game which adds up to 100 points and then declares a winner or loser. The problem im having is when the person rolls a 1 for some reason it rolls again and doesnt go to the computer and lets it roll. I cant figure out what is happening, if the user rolls one it automatically... | As shuttle87 says, your int functions don't return anything. Change them to return void isntead.
As for your problem: http://ideone.com/EEkvy During my test, I rolled 1 three times, one of which the computer rolled after, and twice I got two turns in a row. I'd guess this is because the computer also rolled one, and... |
7,747,857 | 7,750,816 | In CMake, how do I work around the Debug and Release directories Visual Studio 2010 tries to add? | I'm trying to build one of my CMake-based projects from a couple of years ago with Visual Studio 2010 and I'm running into problems to do with the output directory for a project. Visual Studio has always been very keen on adding Debug/ and Release/ subdirectories when outputting binaries, and for various reasons I've a... | It depends a bit on what you want precisely, but I would recommend to take a look at the available target properties, similar to this question.
It depends a bit on what you want exactly. For each target, you could manually set the library_output_directory or runtime_output_directory properties.
if ( MSVC )
set_tar... |
7,748,004 | 7,748,101 | how to manipulate the txt file using C++ STL HOmework | I have a txt file that contains name, id number, mobilenumber, and location in comma separated line.
example
Robby, 7890,7788992356, 123 westminister
tom, 8820, 77882345, 124 kingston road
My task is to retrieve
Look up all of an employee's information by name.
Look up all of an employee's information by ID.
Add t... | #include <string>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <fstream>
struct bird {
std::string name;
int weight;
int height;
};
bird& find_bird_by_name(std::vector<bird>& birds, const std::string& name) {
for(unsigned int i=0; i<birds.size(); ++i) {
if (birds[i].name... |
7,748,070 | 7,748,110 | C++ vararg function pointer | Does the following result in well-defined behavior? That is, if you cast a non-vararg function f as a vararg function g and call g with the arguments that f expects, does the behavior match that of calling f with those arguments?
class Base {};
class Derived1 : public Base {
public:
int getInt1() {return 1;}
};
c... | No, the behavior is undefined, per C++11 5.2.11/6 (reinterpret_cast):
The effect of calling a function through a pointer to a function type that is not the same as the type used in the definition of the function is undefined.
The type of bar is int(Derived1*, Derived2*). The type of the function pointed to by f (the... |
7,748,071 | 7,748,079 | Same random numbers every time I run the program | My random numbers that output, output in the same sequence every time I run my game. Why is this happening?
I have
#include <cstdlib>
and am using this to generate the random numbers
randomDiceRollComputer = 1 + rand() % 6;
| You need to seed your random number generator:
Try putting this at the beginning of the program:
srand ( time(NULL) );
Note that you will need to #include <ctime>.
The idea here is to seed the RNG with a different number each time you launch the program. By using time as the seed, you get a different number each time ... |
7,748,104 | 7,748,277 | Preventing non-const lvalues from resolving to rvalue reference instead of const lvalue reference | I'm having trouble overloading a function to take a value either by const reference or, if it is an rvalue, an rvalue reference. The problem is that my non-const lvalues are binding to the rvalue version of the function. I'm doing this in VC2010.
#include <iostream>
#include <vector>
using namespace std;
template <cl... | When you have a templated function like this you almost never want to overload. The T&& parameter is a catch anything parameter. And you can use it to get any behavior you want out of one overload.
#include <iostream>
#include <vector>
using namespace std;
template <class T>
void display()
{
typedef typename re... |
7,748,133 | 7,748,138 | What is NULL, does it need to be declared? | In this snippet I found here for a simple C++ hash everywhere there is a NULL I get a
NULL was not declared in this scope.
I'm using MinGW compiler g++. My guess is that NULL is not a reserved keyword? How could I determine the version of gcc and look at a reference list for C++ keywords?
This list here states t... | NULL is a standard macro declared in stddef.h. You need to include stddef.h (or cstddef) in order to use NULL.
You can always use 0 in place of NULL, if you don't want to include anything.
|
7,748,195 | 7,748,429 | passing arrays to functions in c++ | I want to pass an array to a certain function in c++. I wrote the following code:
#define nmpart 50
void distances( double (&dis)[3][nmpart][nmpart] )
{
... compute distances which are allocated in "dis"
}
double energy()
{
double dis[3][nmpart][nmpart];
distances(dis);
}
This code is working fi... | Now, a lot of people (including myself) would never write this code professionally (or otherwise) but it basically answers your question. See below for why I'd never write this professionally.
#define nmpart 50
void distances( const double ***dist)
{
... compute distances which are allocated in "dis"
}... |
7,748,299 | 7,748,337 | What does "tree" refer to in breadth and depth based searches? | I need some working snippets on C++ code regarding breadth/depth first searches. Also, in the links below, when using the term tree, is it in reference to a binary tree or more specefically a red and black tree? Or is this a more abstract tree of sorts? Does anyone have a link to working code for these searches...al... | The tree in question is the thing they're searching. It's kinda hard to understand search algorithms without knowing what it is they are searching through.
A tree is a type of graph. A graph is a series of nodes (which presumably represent some data) with connections between certain nodes. A tree is a graph where the c... |
7,748,341 | 7,748,539 | exc_bad_access crash in QT app | I'm writing a QT app and I'm very rusty with C++, so I'm guessing that's the problem. I've got a crash with an exc_bad_access signal on my Mac, which means I'm doing something wrong with memory. Here's my code:
void MainWindowController::showMainWindow() {
MainWindow *w = mainWindow();
w ->show();
}
MainWindow... | Turns out it was something even simpler. I'm used to Objective-C, where ivars are automatically initialized to 0. C++ doesn't do this. So, I had to make sure _mainWindow was initialized to NULL in the constructor. Problem solved.
|
7,748,357 | 7,748,548 | converting 3d position to 2d screen position | I'd like to convert a 3d position into 2d screen position. I had a look at a similar question: Projecting a 3D point to a 2D screen coordinate , but I dont understand it completely. I thought in order to calculate the 2d position I would need the projection matrix, but I dont see how it is used, apart from converting a... | Seems to me it would be something like that:
Vector2 Convert(Vector3 pos, const Matrix& viewMatrix, const Matrix& projectionMatrix, int screenWidth, int screenHeight)
{
pos = Vector3::Transform(pos, viewMatrix);
pos = Vector3::Transform(pos, projectionMatrix);
pos.X = screenWidth*(pos.X... |
7,748,476 | 7,748,528 | overloading pre-increment and post-increment | I saw an example about implementing pre-increment and post-increment, which claims that overloading pre-increment is able to be defined as
T& T ::operator++()
and overloading post-increment can be defined and implemented in terms of pre-incremet as follows
const T T::operator++(int){
const T old(*this);
++(*this);... |
what does "old" mean?
The method is a post increment. The current value ("old value") is returned and then the value is incremented ("new value").
++(*this) is assumed to use the pre-increment, and the original pre-increment definition does not have argument. However, it has *this here.
*this is not an argument. Th... |
7,748,583 | 7,748,627 | In C++, I want to return an array of objects from a function and use it in another | As part of a small project I'm doing to learn Qt, I'm trying to return an array of objects through a function. I then want to retrieve this array properly and use it's content. Right now, I only print a couple values of a single attribute to try and make it work.
The problem I have is that when I try to print its cont... | Use std::vector and std:shared_ptr as in:
std::vector<std::shared_ptr<QLine> > LinesData::getList(){
std::vector<std::shared_ptr<QLine> > lineList2;
for(int i = 0; i < 50; ++i){
lineList2.push_back(new QLine(10, 10*i, 100, 100));
}
return lineList2;}
and
void runtimeWindow::drawAllLines(){
std::ve... |
7,748,666 | 7,748,765 | How to generate two random 1 in one unsigned char in c/c++? | I need to generate a mask vector (unsigned char type) which contains 2 of '1's only, i.e. 0x03, 0x50 and etc.
I also need these two '1's distributed randomly in the vector.
How can I do this in c/c++?
Thank you!
Edit:
A more challenging and general case is asked here.
How to generate n random 1s in an unsigned char a... | I would do like this:
srand(time(0));
int s[8];
for (int i=0; i<8; i++) s[i] = i;
// s[0], s[1] are two random locations for '1's
u = rand()%8;
swap(s[0], s[u]);
v = rand()%7+1;
swap(s[1], s[v]);
unsigned char c = (1 << s[0]) | (1 << s[1]);
|
7,749,066 | 7,749,093 | how to catch out of memory exception in c++? | can anyone please tell me how to catch out of memory exception?
for ex.
try
{
while(true)
{
int i = new int;
}
}
catch( ? <--- what should be put here?)
{
//exception handling
}
and also this,
queue<int> q;
try
{
while(true)
{
q.push(10);
}
}
catch( ? <---- what should ... | Catch std::bad_alloc.
You will also need a strategy for handling the errors, since many of the things you'd like to do will require memory (even if it's only to display an error to the user before shutting down). One strategy is to allocate a block of memory at startup, and delete it in the exception handler before att... |
7,749,497 | 7,749,552 | How to generate n random 1s in an unsigned char array in c/c++? | This is a different question from the one I just asked and it is more challenging.
I have an unsigned char array, say
unsigned char A[16].
I need to generate a mask vector which i will apply to my array A[16].
It should contain n number of '1's, where 0 < n < 16*8 (The mask vector can be an array B[16] as long as the... | Generate random (i,j) pair of numbers, where i < 16 and j < 8. If the bit at position B[i]&(1<<j) is not set, set it and increment "count". Loop until "count" reaches "n".
A bit of code (untested):
void generate_n_bit_mask ( unsigned char B[], int n )
{
// avoid infinite loop later on.
for ( int i=0; (i < 16)... |
7,749,671 | 7,749,722 | How to remove unwanted content from string in c++? | Hi I have a string variable with large content.
I have to remove unwanted line from the string content and keep remaining content as it is.
Following is output that we get after printing the string:
string varString;
cout<<"String content :"<<endl<<varString<<endl;
Output is :
String content :
/abc/def/ghi/klm/run.so... | You can use the function varString.find() to find the position where the string occurs, and then use varString.erase() to erase the text.
|
7,749,700 | 7,749,768 | C++ linked list help (pointers)? | template <typename T>
class LinkedNode
{
public:
T data;
LinkedNode<T> *next;
LinkedNode<T> *prev;
LinkedNode<T>();
LinkedNode<T>(T);
};
// Default constructor
template <typename T>
LinkedNode<T>::LinkedNode()
{
next = NULL;
prev = NULL;
}
template <typename T>
class LinkedList
{
private... | void LinkedList<T>::addFront(T d)
{
LinkedNode<T> temp;
temp.data = d;
...
head = &temp;
...
}
temp is a variable of automatic storage, its lifetime will end as soon as the addFront function returns and you will get a pointer to an invalid object. You have to allocate nodes in the heap, do this ins... |
7,749,882 | 7,750,035 | Boost/thread/locks.hpp(85) compilation error (missing parenthesis) VS2010 | I'm trying to use boost::thread but I can't compile because of an error compiling locks.hpp. I'm using Boost 1.47.0 from BoostPro (precompiled for Windows). (I've been coding for many years, and I've just hit one of those thangs that has me stumped.)
Adding the following include to my code causes the error:
#include... | Something that its included before locks.hpp is defining V as a macro. Just before including locks.hpp add #undef V. That's not the solution though, the solution is to find who is being such a bad player defining a macro named V (at least is all uppercase) and removing it. If applicable, perhaps even file a bug report ... |
7,750,116 | 7,750,184 | Void function is causing compiler error "variable or field ‘funcName’ declared void" | I have declared a helper function to a method of a class I declared in a header file, and for some reason when I compile the source code file I get an error telling me that I declared a variable or field as void. I am not sure how to interpret this since my goal was for the function to be declared void.
The compiler... | First off, you need to qualify kdTree::node because it's declared as an inner struct. Secondly, you have to make insert_Helper a member of your class because node is private.
Extra tip: remove the using directives from the .h files, and rather qualify all your usage of string, etc. Consider including that header in a l... |
7,750,298 | 7,750,392 | WrapperPointer class and deallocation of stack-allocated objects in C++ | I am designing a wrapper class (a bit similar to std::autoPtr but I have different purpose) for scalar values:
template <typename T>
class ScalarPtr
{
private:
T* m_data;
...
public:
ScalarPtr(T *data): m_data(data)
{ ... }
T& operator* ();
T* operator -> ();
~ScalarPtr()
{
if(m_data)
... | I am not sure if there is a better approach other than the boolean flag.
As you are aware(and hence ask the Q)this makes the interface rather non-intutive to the end user.
The purpose of the wrapper/resource managing class is to implement an RAII, where the resource itself takes care of releasing its resources(in this... |
7,750,654 | 7,751,983 | Parse C header file to generate files | I'm working on porting GTK+ to node.js, one difficulty is converting GTK+ functions to corresponding C++ call. For example,
void gtk_window_set_title (GtkWindow *window,
const gchar *title);
G_CONST_RETURN gchar *gtk_window_get_title (GtkWindow ... | node.js seems to be the Javascript implementation of the V8 Javascript engine used by Google Chrome. What you want to create is a new javascript binding for GTK, and this should be done using the GObject-introspection work, not binding each function by hand.
Give a look at what has been done for Gjs and Seed official J... |
7,750,832 | 7,750,882 | Singleton Inheritance Linker Error | I'm new with C++, and I got this linker error,
LNK2001: unresolved external symbol "private: static class DebugLog Singleton::instance" (?instance@?$Singleton@VDebugLog@@@@0VDebugLog@@A)
And here is the problematic codes:
template<typename T>
class Singleton {
public:
static T& getInstance() {
return ins... | You missed:
template<typename T>
T Singleton<T>::instance;
Insert those lines after your class definition.
In order to initialize a static data-member we must include a formal
definition outside the class, in the global scope.
For more information read this link (Section: Static members)
|
7,751,013 | 7,751,235 | Compressing strings with common parts | I have an application that manages a large number of strings. Strings are in a path-like format and have many common parts, but without a clear rule. They are not paths on the file-system but can be considered like so.
I clearly need to optimize memory consumption but without a big performance sacrifice.
I am consider... |
Strings are in a path-like format and have many common parts, but without a clear rule.
In the sense that they are locators in a hierarchy of the form name, (separator, name)*? If so, you can use interning: store the name parts as char const * elements that point into a pool of strings. That way, you effectively comp... |
7,751,242 | 7,751,315 | Does a union always have default value of zero? | Please let us consider following code:
#include <iostream>
using namespace std;
union{
int i;
}u;
int main(){
int k=5;
cout<<k+u.i<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
This code shows me output 5,what means to me is that,variable i in union structure has default value=0, but the sa... |
Does a union always have default value of zero?
The language standard says this:
If an object that has static or thread storage duration is not initialized
explicitly, then:
if it has pointer type, it is initialized to a null pointer;
if it has arithmetic type, it is initialized to (positive or unsigned) zero;
if... |
7,751,292 | 7,751,347 | Wait for a notification in C++ | Not strictly related to C++, I am looking for more of a design patter or suggestion on how to approach this.
Say I have
class A
{
public:
void process();
void wait();
}
I will first call process(), which (duuh) does some processing and will then call wait(). The wait() function is supposed to wait for a notifica... | Pooling for a variable gives terrible performance, because pooling thread takes almost all CPU time. You need to use events or messages - this stuff is platform-specific. You can use some portable library for this, for example, Boost.
|
7,751,437 | 7,751,580 | std::string to LPOLESTR | I have an array of strings like this:
using std::string;
string myArray[] = { string("abc"), string("foo"), string("muh") };
Now I want to use this function:
HRESULT Init(T* begin, T* end, IUnknown* pUnk, CComEnumFlags flags = AtlFlagNoCopy );
T is in my case LPOLESTR. So I need to convert the array of std::string to... | ATL has a set of macros for string conversions. In your case, you can use:
LPOLESTR olestr = A2OLE(std_str.c_str());
Note that OLESTR is basically a wchar_t*, so if you're using std::wstring (or wide char string literals) you don't even need the macro:
LPOLESTR olestr = std_wstr.c_str();
|
7,751,484 | 7,751,553 | Object Reference and Object pointer | What happens, in case of copy constructor, if I use pointer in the parameter instead of reference variable? for ex.
class MyClass
{
private: int a;
char *str;
public:...
...
MyClass(MyClass *pObj)
{
....
....
}
};
| Copy constructor is supposed to make a copy from an object and not from pointer.
Why pass by Reference and not by value? Because if you don't do so, the copy constructor will go in creation of the copy of the argument and it will be an endless loop.
|
7,751,531 | 7,751,881 | How to access html resources file? | I'm using VisualStudio 2008. I have a html file in my win32 project. I wonder is there a way to access html resource files. Can anyone help with this?
| Some code like this gives access to a resource
HANDLE handle = ::LoadLibraryEx("myapp.exe", NULL, LOAD_LIBRARY_AS_DATAFILE);
HRSRC resourceHandle = ::FindResource(handle,resourceId,"resourcename");
DWORD size = ::SizeofResource(handle, resourceHandle);
HGLOBAL dataHandle = ::LoadResource(handle, reso... |
7,751,875 | 7,761,967 | Executing single Boost Test unit test in Visual Studio | I'm trying to get unit testing set up with a c++ project using Visual Studio and Boost Test. I've read all questions on here and elsewhere on the internet about the combination, but although my question seems to be basic I don't find anything about it - so either I'm approaching it wrong or I'm just stupid.
I have a pr... | Normally all unit tests are compiled into one big binary. However, you can run only one test from the command line using the runtime parameters.
For example, if you write two unit tests:
BOOST_AUTO_TEST_CASE( testA )
{
}
BOOST_AUTO_TEST_CASE( testB )
{
}
You may run only the first one using:
my_tests --run_test=testA... |
7,752,215 | 8,076,428 | How to create oauth HMAC-SHA2 signature for facebook | For google i found google oauth playground for creating the oauth signature.
Can anyone of you suggest any nice tutorials or suggest how to create one for facebook
Thanks in advance
| Facebook is not expecting oauth signature parameters
|
7,752,404 | 7,765,108 | SHGetFolderPath': identifier not found | I am doing sample using DirectX 9 On Vs 2008/windows7.
I am getting error.
1>------ Build started: Project: VideoCapture, Configuration: Debug Unicode Win32 ------
1>Compiling...
1>VideoCaptureDlg.cpp
1>.\VideoCaptureDlg.cpp(169) : error C2065: 'SHGFP_TYPE_CURRENT' : undeclared identifier
1>.\VideoCaptureDlg.cpp(169) :... | The Issue is resolved the problem.
I just changed the Preprocessor setting under Project Properties--> c++->
Before it was
_WINDOWS;WINVER=0x0400;DEBUG;_DEBUG;_WIN32_WINNT=0x400;WIN32;UNICODE
I changed it to
_WINDOWS;WINVER=0x0600;DEBUG;_DEBUG;_WIN32_WINNT=0x600;WIN32;UNICODE
|
7,752,617 | 7,752,676 | Exposing a class from Static Library | I am developing a parser library where i parse data and store it in different data structures. The design of the library is such that it will have a DataProvider, Parser and DataStore class. The DataStore is a memebr of DataProvider class. The consumer needs to call the functions in the DataProvider to parse the file a... | If the user doesn't have to use the DataStore directly, it should better not be exposed. You can achieve that by creating an "interface" - abstract DataProvider with only public pure virtual functions. Internally, have a DataProviderImp which will inherit from DataProvider, and contain all the required definitions and ... |
7,753,006 | 7,763,057 | Reading terminal response to bash commands into c++ variable | Does anyone know of a way to read in terminal output from bash commands into c++? For example, entering "ls" into the terminal returns the file names in the current directory, is there any way to perhaps import these names into a string or char array or something? I have been looking at fork(), exec(), and pipe(). I... | Thanks Kerrek SB, I had seen people using popen() in various ways but wasn't sure if that was the route to pursue or not. With the help of the documentation and putting together parts of how other people were using it, I came up with this. This does what the question I wrote asked about specifically: importing the te... |
7,753,145 | 7,753,174 | Customize date format in C++ | I have this function:
void Log::Write(string logline){
//2011-10-12 13:07:40 correct format
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
m_stream.write( asctime (timeinfo), 24 );
m_stream << " - " << logline << std::endl;
}
The output is like this:... | It's very possible. Look at the manpage for strftime(). In this case, you'd want:
void Log::Write(string line)
{
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime (buffer,80,"%Y-%m-%d %H:%M:%S",timeinfo);
m_stream << buf... |
7,753,169 | 7,801,822 | Display QDomDocument as HTML | EDIT
Bounty goes to a decent FOSS-licensed function which will do the conversion.
I have a QDomDocument which is HTML and I want to render it in a widget.
There are loads of QtWebkit classes but they don't seem to use QDom* classes -- QWebPage uses QWebFrame which uses QWebElement.
Is it possible to render the QDomDoc... | QtWebKit is 3-rd party element (Qt port of WebKit engine), and until Qt 4.7 doesn't have anything to do with QtXml module (possibly to keep them binary separate). So either you change your code to create QWebElement's or you will print it to XML and parse again or you will create your own function that traverses your Q... |
7,753,436 | 7,753,542 | Why does TMutex method Acquire() not lock a mutex? | So far I have this code:
****SimpleForm.h****
class TForm1 : public TForm
{
__published: // IDE-managed Components
TMemo *Memo1;
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
TMutex *mtx;
public: // User declarations
__fastcall TForm1(TCompo... | Something else is the explanation to your problem because TMutex::Acquire does indeed acquire a lock on the mutex object. The implementation of TMutex looks like this:
procedure TMutex.Acquire;
begin
if WaitFor(INFINITE) = wrError then
RaiseLastOSError;
end;
procedure TMutex.Release;
begin
if not ReleaseMutex(... |
7,753,477 | 7,753,610 | Store and retrieve a Data structure | I have a situation where I'm parsing an xml file in c++(using libxml) and with the extracted info I'm creating a data structure on the fly & modifying the D.S according to the further extracted info from the parsed file. Now I need to save the D.S as it is, in secondary memory and I want to retrieve back the D.S from ... | I suggest using a library like Boost.Serialization for this.
|
7,753,528 | 7,753,623 | "const const T" in template | The following code compiles and works on G++ 4.4.0 and MS VC2008 Express.
#include <iostream>
template<typename T> struct A{
protected:
T v;
public:
const T get() const{
return v;
}
A(T v_)
:v(v_){
}
};
class B: public A<const int*>{
public:
void doSomething() const{
const... | If T = const int *, then const T is const int * const.
|
7,753,743 | 7,753,846 | class types as private members, MVP? | Because of the most vexing parse, if you have a private member definition in a class header which is a class type like this:
box newBox;
and box has a constructor that accepts no arguments, does that mean you have to either make it a pointer or a reference type?
how do you get around this problem? It seems inelegant t... | The following works just fine:
struct Foo {
}
struct Bar {
Foo foo;
}
No MVP, no ambiguity. Everything is fine. Inside a class-declaration Foo foo; is a member-declaration. It cannot be initialized there, initialization is done (explicitly or implicitly) in the constructor (of Bar in this case).
|
7,753,795 | 7,767,143 | Qt user resize event ends (stops) | I have a QWidget and i need to do some actions (refresh a picture in widget) when resize event ends. How can i catch this action?
I need to catch moment when user ENDs all his resize actions by releasing mouse button. It is not a good practice in my application to refresh image every pixel resized. It should calls only... | Mouse events on windows decoration are managed by the underlying window system, this is why you can't catch them as you tried.
I had the same issue once, the solution I chose was to (re)start a singleshot QTimer on each resize event, and only process the update after the timer interval elapsed. Not very sexy but I did ... |
7,753,866 | 7,753,920 | Thinking in C++ shift operators | I'm reading through a book on C++ standards: "Thinking in C++" by Bruce Eckel.
A lot of the C++ features are explained really well in this book but I have come to a brick wall on something and whether it may or may not help me when I wish to program a game for example, it's irking me as to how it works and I really ca... | if (val & ( 1 << i))
Consider the following binary number (128):
10000000
& is bitwise "AND" - 0 & 0 = 0, 0 & 1 = 1 & 0 = 0, 1 & 1 = 1.
<< is bitwise shift operator; it shifts the binary representation of the shifted number to left.
00000001 << 1 = 00000010; 00000001 << 2 = 00000100.
Write it down on a piece of paper ... |
7,754,144 | 7,754,212 | object type private class members | Both bounding box and cube take a few arguments in their constructor
Header:
#ifndef WALL_H
#define WALL_H
#include "cube.h"
#include "BoundingBox.h"
class Wall
{
private:
Cube* cube;
BoundingBox* boundingBox;
public:
Wall(D3DXVECTOR3 min, D3DXVECTOR3 max);
~Wall();
vo... | Quite simple. Just like this:
#ifndef WALL_H
#define WALL_H
#include "cube.h"
#include "BoundingBox.h"
class Wall
{
private:
Cube cube;
BoundingBox boundingBox;
public:
Wall(D3DXVECTOR3 min, D3DXVECTOR3 max);
void Draw(D3DXMATRIX matView, D3DXMATRIX matProjection);
};
#endif
source:
#include "Wall.h"
Wall::Wall(D3... |
7,754,173 | 7,754,250 | Does functions of a C++ class have only one copy for all objects? | Does the normal functions (and not the static ones) have only one copy for a class in C++, meaning that all the objects refer to the same copy. If so what is the difference between normal function and static function. Also, my teacher was saying that we cannot call static functions of a class using "(object_name).(fun... | If by only one copy you mean all functions have the same location in memory, then yes, you are right. The difference is that static functions don't require an object to be instantiated in order to be called. This also implies that you can't access other non-static members of the class.
As for the initialization, you ca... |
7,754,265 | 7,754,395 | Avoid leaking out external types in a C++ class | I have a class defined in a header like so (abbreviated):
class CairoRenderer
{
public:
CairoRenderer();
~CairoRenderer();
...
protected:
cairo_t* m_context;
cairo_surface_t* m_surface;
};
cairo_t and cairo_surface_t are types defined by the Cairo graphics library.
The problem I have is that if I want ... | You are using the pimpl idiom correctly, and that is your problem. You have hidden the definition of CairoRendererImpl from all external code, including the code in derived classes.
First of all I would like to call into question the value of having a base class that has data members and a non-virtual destructor. You s... |
7,754,266 | 7,754,686 | MFC: new object - error message? | I have a class (Event.h):
class CEvent
{
public:
CEvent();
~CEvent();
int nVal;
};
defined in Event.cpp
#include "event.h"
CEvent::CEvent() {}
CEvent::~CEvent() {}
In a different class I have included "event.h" and am trying the following:
CEvent* pEvent = new CEvent();
But Im getting a compiler err... | Found the problem:
#ifdef _DEBUG
#define DEBUG_NEW
#endif
was included in a different class. This was impacting 'new' everywhere! Commenting this out clears the error.
Go figure.
|
7,754,315 | 7,755,460 | Where to learn Hardware Programming? | I have been doing some web development, and now I want to know further more about programming so, these Hardware Programming stuffs excite me. I could not find a proper place to start to learn this process. So can you provide any better place ? I want to know better about C or C++ to do hardware programming. Is there a... | There are boards you can get for $10 or less that have things like leds that you can start with getting comfortable programming at that level, then expand that knowledge. I have example programs for a number of sub $100 (usually under $50) boards at github.
The msp430 launchpad is $4.30 for example and the stm32 val... |
7,754,390 | 7,754,425 | Static class member, which is a struct | I have a class in which I would like to have a static member which is a struct.
for example:
.h file:
typedef struct _TransactionLog
{
string Reference;
vector<int> CreditLog;
int id;
}TransactionLog;
class CTransactionLog {
static TransactionLog logInfo;
public:
static void Clear();
static Tra... | You need to initialize your static member in the cpp file:
//add the following line:
TransactionLog CTransactionLog::logInfo;
void CTransactionLog::Clear()
{
logInfo.Reference = "";
logInfo.CreditLog.clear();
logInfo.id = 0;
}
TransactionLog CTransactionLog::getLog()
{
return logInfo;
}
|
7,754,532 | 7,754,656 | virtual destructor fail using array | I found this code on a web site
#include <iostream>
using namespace std;
struct Base
{
Base() { cout << "Base" << " "; }
virtual ~Base() { cout << "~Base" << endl; }
int i;
};
struct Der : public Base
{
Der() { cout << "Der" << endl; }
virtual ~Der() { cout << "~Der" << " "; }
int it[10]; //... | Base *bq = new Der[5];
delete [] bq; // this causes runtime error
The reason is arrays are not treated polymorphically. Therefore, in the above code, the delete statement invokes undefined behaviour.
§5.3.5/3 C++03 says
In the first alternative (delete object), if the static type of the operand is different from i... |
7,754,564 | 7,754,789 | clang++ error message when using C++0x: call to deleted constructor of | Hello I have upgraded my Xcode to version 4.2 and clang++ to version:
Apple clang version 3.0 (tags/Apple/clang-211.10.1) (based on LLVM 3.0svn)
Target: x86_64-apple-darwin11.2.0
Thread model: posix
When try to compile the following code with clang -std=c++0x
#include <memory>
#include <limits>
#include <boost/shared... | This looks like a clang bug to me. I'm working with a later clang version which does not have this behavior. You might try giving ilpConstraint an explicit copy constructor as a temporary workaround.
|
7,754,577 | 9,992,555 | How to reinitialise an embedded Python interpreter? | I'm working on embedding Python in our test suite application. The purpose is to use Python to run several tests scripts to collect data and make a report of tests. Multiple test scripts for one test run can create global variables and functions that can be used in the next script.
The application also provides extens... | Here is another way I found to achieve what I want, start with a clean slate in the interpreter.
I can control the global and local namespaces I use to execute the code:
// get the dictionary from the main module
// Get pointer to main module of python script
object main_module = import("__main__");
// Get dictionary o... |
7,754,585 | 7,754,622 | Boost Licensing changes | I have couple of questions regarding boost licensing,
Is it that all the boost libraries have the same "boost licensing" or does it vary for some libraries?
Has there been any recent changes in licensing for some boost libraries?
I tried to find information by simple search but could not get any specific information.... | It is the same license for every library in Boost.
|
7,754,621 | 7,754,673 | C++ header-only include pattern | I would like to write code in .hpp without separation to .h and .cpp
I did it. I use .cpp only for static class-fields definitions
I would like not to write #include manually ...
I use forward delarations where it possible.
Every my .hpp file containt #pragma once.
But, when my project grows up to 40-50 classes i sa... | Unfortunately you're possibly using the wrong language. There are some things that are just much in C++ easier when you separate the class definition from implementation. Even with forward declarations you'll probably still wind up with circular dependencies that can only be resolved by moving implementations into sepa... |
7,754,672 | 7,754,877 | read attributes name in C++ using xerces | void MySAX2Handler::startElement(const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs)
{
char* message = XMLString::transcode(localname);
cout << "first element: "<< messag... | http://xerces.apache.org/xerces-c/apiDocs-3/classAttributeList.html
for (int i=0; i< attrs.getLength(); i++)
{
std::cout << attrs.getName(i) << std::cout << attrs.getValue(i) << std::endl;
}
I'll leave looking up by name and/or transcoding and/or namespace resolutions up to you :)
|
7,754,713 | 7,754,759 | C++ - constant and optimization | I am optimizing some hotspots in my application and compilation is done using gcc-arm.
Now, is there any chance that the following statements result in different assembler code:
static const pixel_t roundedwhite = 4294572537U;
return (packed >= roundedwhite) ? purewhite : packed;
// OR
const pixel_t roundedwhite = 429... | Call gcc with the -S flag and take a look at the assembly:
-S
Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified.
I would it out try myself to include in the answer, but I don't have an ARM compiler handy.
|
7,754,883 | 7,754,935 | best practice for parameters? | Is it generally considered better to pass parameters as pointers rather than as value when you can? Obviously it largely depends on the situation, but when there is a choice, is it better to use pointers?
Is this simply for reasons of memory?
And what is better to pass through if it is true, a pointer or a reference?
| Some general rules of thumb:
If you need to modify it, pass a pointer or a reference. If the value might be null, pass a pointer, otherwise pass a reference.
If it's large, pass a const pointer or const reference, depending on whether null is a legal value.
If using pointers, prefer smart pointers to bare pointers.
Oth... |
7,755,071 | 7,755,144 | Bitwise unpacking using signed data | I've been trying for a while pack & unpack some chars into an integer. Although there are some topics related to this question, my problem is related with the signed shift. I don't get the 'trick' to unpack a signed value, i.e.:
char c1 = -119;
char c2 = 26;
// pack
int packed = (unsigned char)c1 | (c2 << 8);
// unpac... | You are casting c1 to unsigned char after shifting it out of the range of that type, so the result of the cast is zero. You should do the cast before shifting:
int packed = (unsigned char)c0 | ((unsigned char)c1 << 8) | (c2 << 16);
|
7,755,202 | 7,755,280 | Multi-character constant warnings | Why is this a warning? I think there are many cases when is more clear to use multi-char int constants instead of "no meaning" numbers or instead of defining const variables with same value. When parsing wave/tiff/other file types is more clear to compare the read values with some 'EVAW', 'data', etc instead of their c... | According to the standard (§6.4.4.4/10)
The value of an integer character constant containing more than one
character (e.g., 'ab'), [...] is implementation-defined.
long x = '\xde\xad\xbe\xef'; // yes, single quotes
This is valid ISO 9899:2011 C. It compiles without warning under gcc with -Wall, and a “multi-char... |
7,755,244 | 7,755,333 | Syntax for partial class template specialization | In the following, am I forgetting some correct syntax for partial specializing class NumInfo or is it even possible to do that?
template<typename T>
struct NumInfo {
T x;
T y;
void Print();
};
template<typename T>
void NumInfo <T>::Print() {
/*.....*/
}
template<typename T>
struct NumInfo <float> {
... | Your design has a problem -- right now you have multiple classes with the same name NumInfo<float> and different definitions (depending on T). To fix that, you'll need a second template parameter, like this:
template<typename S, typename T=S>
struct NumInfo
{
T x;
S y;
void Print();
};
template<typename ... |
7,755,257 | 7,755,323 | Will a static variable always use up memory? | Based on this discussion, I was wondering if a function scope static variable always uses memory or if the compiler is allowed to optimize that away. To illustrate the question, assume a function like such:
void f() {
static const int i = 3;
int j = i + 1;
printf("%d", j);
}
The compiler will very likely inli... |
So is the compiler allowed to optimize the static away[...] ?
Yes. According to the Standard:
1.9 Program Execution
The semantic descriptions in this International Standard define a
parameterized nondeterministic abstract machine. This International
Standard places no requirement on the structure of conforming
... |
7,755,376 | 7,755,877 | In-explicit constructing in operator overloading? | Is it possible use in-explicit constructing with operators ?
Just like in this example (which does of course not work):
class myFoo {
public:
double x, y;
myFoo(double, double);
void operator [] (myFoo);
};
int main() {
myFoo f1(0.0, 1.1);
f1[ {9.9, 10.0} ]; /// or wha... | C++11 allows an initializer list to be passed to an overloaded operator [] (see 13.5.5).
You'd need something like
void operator[](std::initializer_list<double>);
That would match your original syntax of f1[ {9.9, 10.0} ];.
|
7,755,382 | 7,776,541 | Static Linking in Fortran | I've developed a module written in C++ that manages the licenses for my company's product. To prevent DLL replacement, it is our goal to statically link the DLL in the solution. This is very easy to do in C++ but proving to be a bit problematic for part of our codebase that is written in Fortran.
I realize that this c... | To get static linking, the usual way is not to use DLL but simple libraries instead (*.lib). This has nothing to do with programming languages : it just depends on the operating system.
Building a library is also simpler than building a DLL. On Unix, a library has the suffix .a whereas a DLL has a suffix .so (for share... |
7,755,423 | 7,755,492 | Read file in binary and output in hex std::cin to std::cout | I was trying to achieve this using this code:
char c;
while (std::cin >> c)
std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<uint32_t>(c);
but it looks like it gets messed up reading in nulls (all nulls are removed from my file). How can I fix this?
| The input stream operator typically requires a separator, you should read a buffer from the file, something like shown here: http://www.cplusplus.com/reference/iostream/istream/read/, then iterate over the contents and print out, you may also want to use showbase to make the hex output prettier...
EDIT: try something l... |
7,755,557 | 7,755,695 | Boost.Flyweight memory consumption | I'm just reading an article about Boost.Flyweight Performance
As you can see in the link the overhead of the factory is
- for hashed_factory: ~2.5 * sizeof(word)
- for set_factory: 4 * sizeof(word)
The basic question is .... why 4 words for set and not zero ?
As far as I know, using a hash implies computing ... | Each node of the RB tree contains a pointer to the left child, pointer to the right child, the color and one piece of data. The first three count as overhead, which means it isn't 0. I'm not quite sure why they say it's 4 when the 3 elements fit easily in 3 words, but maybe they count in something else (like the parent... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.