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
5,600,827
5,600,846
returning enum from function in C++ base class
I came across the following code, class Handler { public: Handler() {} ~Handler() {} enum HANDLER_PRIORITY {PRIORITY_0, PRIORITY_1, PRIORITY_2}; virtual HANDLER_PRIORITY GetPriority(); private: HANDLER_PRIORITY m_priority; } in the .cpp file I have this HANDLER_PRIORITY Handler::GetPrioity() { r...
You need Handler::HANDLER_PRIORITY Handler::GetPriority() { ... } Edit: Sorry didn't see the rest of your post. As for why this is the case, HANDLER_PRIORTY doesn't have global scope. It's a member of Handler no less than any other. So of course you have to tell the compiler where it is, i.e. use Handler::.
5,600,995
5,601,019
Can I extract function arguments from a function pointer?
Can I extract extra information (like number of arguments and their types) from a function pointer? If (most likely) not, what is the best way to allow a programmer to pass in a function pointer and the variable number of arguments EDIT: I meant that it should allow functions with different number of arguments that it ...
You can get the arity, return type, and parameter types of a function using function_traits from the Boost.TypeTraits library. To fully enable your described scenario of having what is effectively a variadic function that is type safe, you really need variadic templates, a new feature being added in C++0x and supported...
5,601,051
5,601,076
static member variable in a class
Possible Duplicate: What is an undefined reference/unresolved external symbol error and how do I fix it? Why do I have a "undefined reference to Monitor::count" error for the following code? Thanks! #include <iostream> using namespace std; class Monitor { static int count; public: void print() { cout << "i...
Because you declare it but do not define it. Put the following in one (and only one) of your .cpp files: int Monitor::count = 0;
5,601,303
5,607,311
Boost any_range vs. "canonical form" - what is the latter?
Boost's any_range documentation says the following: Despite the underlying any_iterator being the fastest available implementation, the performance overhead of any_range is still appreciable due to the cost of virtual function calls required to implement increment, decrement, advance, equal etc. Frequently a better de...
I think they mean converting your range to an std::vector, or whatever the standard container is in your project, and returning an iterator into that. The tradeoff is between the cost of making a copy of your range from the original range type to the canonical container type, and the cost of heap allocations and virtua...
5,601,416
5,601,481
c++ return data in a value parameter?
I'm trying to understand the difference between void getval(const int record, int32* val, bool allowExc) const; and void getval(const int record, vector<int32>* value, bool allowExc) const; I need to return a list of int32s. Can the 1st example return a list of ints32s or only one? Any help is appreciated
The difference is obviously between int32* and vector<int32>*. While the two are doing basically the same thing you should know that int32* is a primitive data type ( a pointer to an array of int32s) while vector is a STL (Standard Template Library) class holding in this case an array of int32s while offering more opti...
5,601,582
5,601,601
Using C++, while making a console application is there a way for cin to accept the next character entered and continue without hitting enter?
We just covered screen control in my C++ class and I want to make a console app where you can move a "X" around the screen with the use of w,a,s,d, but I don't want the user to have to hit enter.
This is not possible with standard C++. You will need a cross-platform library like pdcurses or the conio library (originally from DOS), or a related platform-dependent library.
5,601,831
5,601,898
I've done a shady thing
Are (seemingly) shady things ever acceptable for practical reasons? First, a bit of background on my code. I'm writing the graphics module of my 2D game. My module contains more than two classes, but I'll only mention two in here: Font and GraphicsRenderer. Font provides an interface through which to load (and release)...
In general, if something looks sketchy, I've found that it's often worth going back a few times and trying to figure out exactly why that's necessary. In most cases, some kind of fix pops up (maybe not as "nice", but not relying on any kind of trick). Now, the first issue I see in your example is this bit of code: stru...
5,601,907
5,601,921
What kind of hash function can give me a 32 bit value from a string?
I'm using the QT framework so if there is something like this implemented in that, I would use it, but I couldn't find it. I would like to get random color values for variable length strings.
If you include <QHash>, then you get overloads of the function qHash(), one of which is: uint qHash(const QString & key)
5,601,948
5,602,005
How to return a const ref to a struct object such that all its nested structures also are read only?
How do I prevent all the member variables in a nested struct to be non modifiable? typedef struct A { int a; int b; }A1; typedef struct B { A1* objA; }B1; class C { public: const B& GetB() const { return objB; } PopulateB(); private: B objB; }; int main() ...
The pointer type in your struct B refers to a non-const value, and this is the definition that counts. If you wanted to control access, you should hide data members and provide accessors and mutators: struct B { private: A1* objA; public: A1 & a1() {return *objA;} A1 const & a1() const {return *objA;} };
5,601,950
5,791,452
How to build Qt for Visual Studio 2010
I struggled finding a how-to which provides a stable solution for using Qt with Visual Studio 2010, so after collecting all the bits of information and some trial and error, I would like to write my solution into a guide. The problem, or why is it not possible to use prebuilt binaries? It seems that using binaries buil...
First of all, it’s very important to understand that for using Qt with Visual Studio 2010, it's not possible to use the pre-built binaries which were made for Visual Studio 2008, but you have to compile it from source. Downloading Qt On https://www.qt.io/download/ Update 2017: the latest Qt 4.x branch (Qt 4.8.6) has 2 ...
5,601,965
5,905,817
OpenCV::ML - is it possible to tell openCV which parts of data we want to send to which neuron?
So here is shown a simple example - 2 floats as data + 1 float as output: Layer 1: 2 neurons (2 inputs) Layer 2: 3 neurons (hidden layer) Layer 3: 3 neurons (hidden layer) Layer 4: 1 neurons (1 output) And we create ANs with something like cvSet1D(&neuralLayers1, 0, cvScal...
I would definitely use the KNN mentioned.
5,602,029
5,602,174
what's the best way to display images in qt? also I would like to zoom in to particular areas as well
I've been using label to display images. I'd like to be able to click and create a bounding box then be able to drag the cursor to move around in the image. What would I need to do this? Thanks.
I'm not 100% sure I understand what you are trying to do, but I think the QGraphicsScene is what you are looking for. You can (among many other things): Render images (QGraphicsPixmapItem, for example) Change the zoom level when rendering the scene on a QGraphicsView. Select things using a "rubber band" Move items aro...
5,602,030
5,602,057
How can i use member initialization list to initialize an array?
class A { public: A(); private: char a[5]; int* ptr; }; A::A() : a(0), ptr(0) { } Is this right?
The only sensible thing you can do with a C-array in C++03 is value-initialize it (in C++11 and beyond it can be list-initialized). From the C++03 standard, §8.5/7: An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized. And from §8.5/5: To value-initialize an object of type...
5,602,112
5,602,136
When to Overload the Comma Operator?
I see questions on SO every so often about overloading the comma operator in C++ (mainly unrelated to the overloading itself, but things like the notion of sequence points), and it makes me wonder: When should you overload the comma? What are some examples of its practical uses? I just can't think of any examples off t...
Let's change the emphasis a bit to: When should you overload the comma? The answer: Never. The exception: If you're doing template metaprogramming, operator, has a special place at the very bottom of the operator precedence list, which can come in handy for constructing SFINAE-guards, etc. The only two practical uses...
5,602,121
5,602,141
about argument to member function
Will adding an argument to member function gonna change the behavior of the function? Need help about this concept.
The behavior won't change if you only add an argument to the prototype of the function. However you will have to change all the call to this function since the prototype changed, this isn't the same function anymore. And sincerely, I don't see the point of adding an argument if you don't modify the code afterward.
5,602,296
5,602,329
bind: Socket operation on non-socket
I writing a server and a client and keep getting 'bind: Socket operation on non-socket'. I've researched the heck out of this, have other code that runs in another application and have exhausted 8 hours trying to find this bug. The code is: void TCPSocket::buildTCPSocket(int port) { initializeSocket1(); getSock...
I can almost guarantee you that you're getting that error because you never initialized socket1. Typically you have to do something like this: int socket1 = socket(AF_INET, SOCK_STREAM, 0); bind(socket1, ...); I don't see any code anywhere in there for setting up socket1. This is what the error message is telling yo...
5,602,435
5,602,461
OO: how to create a function "addFruit" to add fruit into a vector<fruit>
I have: class fruit { } class apple:fruit { } class pear:fruit { } I want to create a function "addFruit" to add fruit into a vector of fruit. like: vector<fruit> fruits; How can I do it? edited: I tried put a virtual function in base class. and do the really operation in subclass. But it failed. I got a lot of err...
To properly use inheritance you'd want to do something like this: #include <iostream> #include <vector> class Fruit { public: virtual void Eat() { std::cout << "Mmm.. a fruit!" << std::endl; } virtual ~Fruit() {} }; class Apple : public Fruit { public: void Eat() { std::cout <<...
5,602,533
5,602,562
Is there any way I can tell if my code is being compiled with cl.exe?
This has probably been asked before, but I couldn't find it. Is there a way to determine, at compile time, if my code is being compiled by cl.exe? I will be using this to conditionally include (during preprocessing, via #ifdef) certain #pragma directives only supported by cl.exe.
If you want to make decisions on the cl.exe version, use _MSC_BUILD. However, first check for _MSC_VER, because _MSC_BUILD was not available in VS 2005.
5,602,996
5,603,012
Add build date (VS 2010 - C++)
Recently I built a game in XNA and in the AssemblyInfo source file I could set AssemblyVersion to x.x.* and it would set the build and revision to the date and time the project was compiled on. I am now doing a project in C++ and I am wondering how I can duplicate that functionality. Both so that the exe file displays ...
You can use the __DATE__ and __TIME__ macros.
5,603,101
5,603,123
Resolving a linker error: undefined reference to static class members
My code is Arduinoish. I turned on verbose compiling so I could verify that all the .o files are indeed getting passed to the linker correctly, and they are (linker command below). This leads me to believe that it is some sort of syntax error. Googling for the error "undefined reference to in function" produces a lot...
You have to define your class statics in a source file some where. Putting them in the class just declares that they are there, but something still needs to define them. Inside your .cpp file your can do so like this: NewSoftSerial SerialServoControl::_serial(9, 8); char SerialServoControl::_tx = 0; char SerialServoCon...
5,603,310
5,603,451
about make_heap algorithm in C++
http://www.cplusplus.com/reference/algorithm/make_heap/ In this link. it says: Internally, a heap is a tree where each node links to values not greater than its own value. In heaps generated by make_heap, the specific position of an element in the tree rather than being determined by memory-consuming links...
What this says is that a heap has a typical tree like structure, where each 'parent' node is greater than or equal to the value of the 'child' node ("...where each node links to values not greater than its own value..."). It then goes on to say that instead of using links (i.e. pointers in, say, a struct (like you woul...
5,603,497
6,006,403
Best software to convert EMF file to GDI commands?
I can't read the EMF binary file. When I hex-dump it, I still don't understand it. Is there any software to read GDI commands from an EMF file? Thanks.
I found this, it's good! It can convert emf to GDI or GDI+ commands. http://frazmitic.free.fr/emfexplorer/index.htm
5,603,505
5,604,749
How can I draw a tilemap without my ram useage or cpu useage going way up?
Okay, so I'm trying to draw a tilemap on the screen with SDL, and my fps is really bad cause of it. And I've tried doing it in SFML a different way, but that way makes my ram useage go way up. the way I'm trying to draw it in SDL is having a SDL_Surface *tilemap; that I chop up, and render like this: void apply_surface...
Make sure that when you load tilemap, that you convert it to the same format as the screen, so that blitting doesn't have to perform any conversion. SDL_DisplayFormat does this for you. Where are you calling render()? Make sure it's called once per frame, no more, no less.
5,603,561
5,603,572
Xcode: strict C compilation?
When I use Xcode (3.1.4 Leopard) to code in plain C (using the "Standard Tool" template that creates a "main.c"), the compiler behaves like a C++ compiler. It allows single-line comments (like "// comment here"), it allows declaring a variable in the for-loop initializer (like "for(int i = 0; ...)"), it even allows inl...
All of those so-called "C++ features" are in fact part of C. All three were added in C99. If you are compiling using GCC, you can use the -std=c89 to force the compiler into C89/C90 mode.
5,603,625
5,603,845
How to check if a HANDLE is valid or not?
In C++, I have opened a serial port that has a HANDLE. Since the port may close by an external application, how can I verify that the HANDLE is still valid before reading data? I think it can be done by checking the HANDLE against a suitable API function, but which? Thank you.
Checking to see whether a handle is "valid" is a mistake. You need to have a better way of dealing with this. The problem is that once a handle has been closed, the same handle value can be generated by a new open of something different, and your test might say the handle is valid, but you are not operating on the file...
5,603,897
5,603,941
Why Inheritance influences Exception handling?
While finding answer for this query with writing test code, I got to know that private/protected inheritance changes the way exceptions are received from various classes, which was very surprising. To find the answer I referred earlier forum questions and I came across this similar question. For me it's quite obvious t...
The meaning of private and protected inheritance is that no one outside of the class or class hierarchy can know about the inheritance. This is the same way as no one outside the class can know about a private member. Catching a derived class by its base class revealed to the catcher that the derived class is infact de...
5,604,024
5,604,389
const boost::array<T,N> or boost::array<const T,N>?
What is difference between these two? Which one you would prefer when you need a fixed size array of constant values? const boost::array<int, 2> x = {0, 1}; boost::array<const int, 2> y = {0, 1}; Thanks.
The second one will prevent that you copy it to a new non-const array boost::array<const int, 2> y = {0, 1}; boost::array<int, 2> y1 = y; // error! Since I would expect that to work, I would probably go with the first option. Passing the second one to templates that expect a boost::array<T, N> will prevent those templ...
5,604,099
5,604,151
How can I chart 3d scatter graphs in C++?
What is the best way to chart a 3D scatter graph in C++? Or maybe it's easier to use an external programs. Can you recommend my anything?
What you'll want is some form of GUI library - you could use, say, ncurses, but graphs in a terminal are rather difficult. Any GUI library will do it. FLTK is the easiest to pick up and can definitely accommodate your problem, but GTK should also do it, along with wxWidgets et al. Failing that, OpenGL is probably a hac...
5,604,290
5,604,461
adding string literal to static_assert
Is there a way to combine what's going to be output by static_assert? What I mean is this: template<class T> struct X { static_assert(std::is_signed<T>::value, "Type " + T + " must be signed.");//this doesn't work };
On the basis that this does not compile int main() { const char c[2] = "1"; static_assert(1==1, c) } nor this int main() { const char* c = "1"; static_assert(1==1, c) } Both with errors error: expected a string literal then I would have to conclude that it is not possible. "A string literal consists of ze...
5,604,610
5,604,827
Sending UDT over RPC in Windows
I'm getting to grips with RPC in Windows and I've got a basic client/server model setup and working and I can pass a string over between the 2 OK but I now need to extend it to pass a binary structure between the 2 and I can't figure out how to. Obviously trying to pass a void* will not work as the MIDL compiler would ...
Your object has two string and an int. You can define such an object in the IDL source file and pass them around after the compiler spits out the necessary stubs. Start here to do the reading.
5,604,796
5,684,683
"ALWAYS use a named regex, NEVER a temporary" - why?
Stephan T. Lavavej in his regex presentation mentions that one should never use temporary regex object. I could think of some efficiency reasons of course. But it looks like there are more "explicit" reasons to avoid temporary objects. A sample code stops working once I replace a named regex with a temporary one. Do yo...
Thinking more about the issue I have realized that constructor of regex_iterator takes a reference to regex, which of course explains the problem. Passing a reference to a temporary object is obviously a mistake.
5,604,841
5,604,871
Why aren't data instances NULL by default?
Something that has always bothered me is why isn't data set to NULL by the compiler, if nothing else was specified? I can't see any reason NOT to, and surely it must be better than the junk that gets referred to otherwise?
The original reason was "for speed" -- the variables were only going to make sense once you assigned something to them, so there was an effort to not make a pointless initialization to 0 that was just going to be overwritten by the programmer in a few milliseconds with the actual data anyway. While it isn't exactly exp...
5,604,848
5,604,941
Invoking the copy constructor of a base class for boost pointer containers?
For the below code, when v is copied, the members of Model class do not get copied. #include <boost/ptr_container/ptr_vector.hpp> #include <iostream> using namespace std; class SomeNewClass { public: int a; }; class Model { public: int i; SomeNewClass* s;//A deep copy ...
(1) To invoke Model copy constructor, change your ModelInherit copy constructor like following: ModelInherit(const ModelInherit& m): Model(m), j(m.j) {} (2) Deep copy can be done like this: Model(const Model& m): i(m.i), s(0) { if(m.s != 0) this->s = new SomeNewClass(*(m.s)); cout<<"Model Copy ctor invoked"<<e...
5,604,906
5,604,939
Social network architecture, C++ Clients Neo4j database what between?
I'm currently working on the implementation of a social network. The architecture is: - Distributed C++/Qt clients - Neo4j server database I could directly query the database since it has a REST interface from my Qt apps. I'm not quite comfortable with this approach because it is not secured, and no optimizations (cac...
REST will be fast enough. Use it until you can measure and have some real data that tells you it's a problem. But I wouldn't use the REST API to deal directly with the database. I'd add layers between the two that manages security, validation and binding, use cases and error handling, logging, transactions, etc. If yo...
5,605,017
6,401,337
Strange file-permissions if apps run as administrator
My program must be run as administrator and creates some files. If I run it manually by right-click on the icon and selecting "run as administrator" -- everything okay -- all users have access to created files. But if program launched from the another program by ShellExecuteEx with "runas" verb -- created files have no...
Why not setup the linker flag (VC2008 and higher): Linker -> Manifest -> UAC Execution Level: requireAdministrator (/level='requireAdministrator') EDIT: I re-read the question, and found that problem is probably with NTFS file-security. This is not your program's fault, but this is by design. Any user who creates files...
5,605,071
5,649,454
How to access various members of a target class from undo/redo command base class
I've implemented an undo /redo framework and have a set of command classes that support changing various attributes of the character class. There are several 10+ derived classes each of which is almost exactly the same except for the specific attribute of the character class it operates on. I would like to push this...
The solution I came up with seems to work out very well. I'm going to post it for other's reference and to see the community response. Thanks I changed the CharacterCommand base class into a template class: template<typename DO_TYPE, typename UNDO_TYPE> class CharacterCommand : public TextBoxCommand { public: ... /...
5,605,076
5,605,112
Order of template arguments for a function
In below code among 2 template arguments, I use one of them implicit and another explicitly: class A {}; template<typename ToType, typename FromType> ToType CompileTimeCast (FromType pointer) { return (ToType)(pointer); } int main () { A *pA; int *pi = CompileTimeCast<int*>(pA); // function invocation } It wor...
By swapping if you meant this: template<typename FromType, typename ToType> //argument swapped their position! ToType CompileTimeCast (FromType pointer) Then the argument deduction wouldn't work anymore. Because when you write CompileTimeCast<int*>, then compiler would assume that int* is always the first argument in ...
5,605,125
5,605,159
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
I just found a comment in this answer saying that using iostream::eof in a loop condition is "almost certainly wrong". I generally use something like while(cin>>n) - which I guess implicitly checks for EOF. Why is checking for eof explicitly using while (!cin.eof()) wrong? How is it different from using scanf("...",....
Because iostream::eof will only return true after reading the end of the stream. It does not indicate, that the next read will be the end of the stream. Consider this (and assume then next read will be at the end of the stream): while(!inStream.eof()){ int data; // yay, not end of stream yet, now read ... inStrea...
5,605,142
5,612,606
std::max() and std::min() not constexpr
I just noticed that the new standard defines min(a,b) and max(a,b) without constexpr. Examples from 25.4.7, [alg.min.max]: template<class T> const T& min(const T& a, const T& b); template<class T> T min(initializer_list<T> t); Isn't this a pity? I would have liked to write char data[ max(sizeof(A),sizeof(B)) ]; inste...
Critical Update The below analysis is wrong, because it confuses one important thing. The following statement I did missed one important detail, which requires an entirely different answer. The unnamed reference max returns will refer to that operand. The problem here is that function invocation substitution is done ...
5,605,186
5,605,237
State machine for Simulator
Hi all I am working for the simulator of the gateway.gateway is a device which is connected with camera and stream video to the server whenever server request it. Each gateway is connected with more than one camrea. Simulator can simulate 1000 gateway. Now here each gateway has state like booting,disconnected,ready etc...
I would say no. Normally in discrete-event simulation the simulation itself isn't represented as an object, nor does the overall simulation have distinct states of its own.
5,605,270
5,605,317
I continue to get garbage values in an array that have been modified from another array, in a function
I'm a bit new to programming so the answer to my problem has not become obvious, although I have tried to accomplish the task a number of ways. The issue is that I'm trying to take an array of words, remove any punctuation from the array, and place the new words into a separate array. I attempted to do this but I keep...
Not sure what you mean by gargage output? If I call your function with this (g++ 4.4.5) #include <string> #include <iostream> using namespace std; int main (int ac, char **av) { int numwords = 3; string sepwords1[] = {"one,", "two", "three"}; string sepwords2[numwords]; norm(sepwords1,sepwords2,numwords); ...
5,605,714
5,606,752
Using MPI_Gather for 3d array in c++?
I am trying to parallelize a for loop operation which is sandwiched between two for loops. After the data (3d array) is calculated in each processor I want to collect the data from each processor back to the root node for my further processing. I tried using the MPI_Gather function to get the data back to the root node...
The issues here are actually similar to the issues in 2d: MPI_Type_create_subarray and MPI_Gather ; there's a very lengthy answer there that covers most of the crucial points. Gathering multidimensional array sections is trickier than just doing 1d arrays, because the data you're gathering actually overlaps. Eg, t...
5,605,757
5,605,776
What are "exotic character sets"?
I am reading an c++ document, it said as this, Wide characters are used mainly to represent non-English or exotic character sets. What's the exactly meaning for exotic character sets?
I think it has no "technical" meaning, it's used as in "strange" or "unusual" character sets. Since we're talking about wide characters, in general we are actually talking about Unicode; I'd say that Cuneiform or Klingon1 could be considered as "exotic character sets". Or even those Unicode blocks not intended for lang...
5,605,762
5,605,764
Class objects passed as parameters, accessing their own private members
class Foo { public: void someFunk( Foo &bar ); private: int a; ... }; void Foo::someFunk( Foo &bar ) { a = bar.a; } I noticed that objects passed as parameters are allowed to access private data members. I can see why for the this pointer, but shouldn't an object passed as a parameter have to call an accessor? I thou...
I don't know what the official rationale is for this, but it seems to me that being able to access private members of another object of your own class does not break encapsulation, nor does it create any additional coupling. The point of encapsulation is that an object of class A should not know the inner workings of a...
5,605,845
5,606,413
Dynamic Qt string translation
If we wrap strings in tr() we can use the linguist to translate qt apps. The following example is one way to dynamically load a language: int main(int argc, char *argv[]) { QApplication app(argc, argv); QTranslator translator; translator.load("hellotr_la"); app.installTranslator(&translator); ...
You don't have to use the provided tr convenience functions, nor do you have to install the translators. Just look at the API for QTranslator and you'll see that you can call translate directly. IF you go this route you can simply have a map of translators available and lookup the text as needed. If you must use tr the...
5,606,039
5,606,125
Printing Vector on Console
I have a vector of type template class and I am trying to print it, but getting a weird error. Here is my class: template <typename VertexType, typename EdgeType> class Vertex{ private: typedef std::vector<std::pair<int, EdgeType> > VertexList; std::vector<Vertex<VertexType, EdgeType>> Vertice; public: voi...
You aren't defining an operator << anywhere. You should define it like this out of your class : template <typename VertexType, typename EdgeType> std::ostream& operator << (std::ostream& out, const Vertex<VertexType,EdgeType>& v); // implementation template <typename VertexType, typename EdgeType> std::ostream& operato...
5,606,047
5,614,209
Flex real type definition in scientific and engineering notation in c++
I'm defining a real type and I'm using strtod for the exponential way even though is untested and don't really know if it works but more imporantly I would like to know if there is any built in function like strtod for engineering notation and if there isn't, how can I do it? Thanks in advance, Martin
strtod understands exponential notation. See, e.g., http://pubs.opengroup.org/onlinepubs/009695399/functions/strtod.html .
5,606,064
5,606,093
confusion on a const function that is calling a non-const function
Basically there are three classes I defined: paralelogram, point and line classes, and paralelogram has some vectors of points and lines, and in the paralelogram class I am defining a compute_area function as double Paralelogram::compute_area() const { assert( !points.empty() ); double h = points[3].distance_to_lin...
In a const function, types of every member becomes const in such a way that you cannot modify them (unless they're declared mutable), nor can you call any non-const function using them. It seems that in your code, distance_to_line is non-const function, but you're calling it from a const function, that means inside con...
5,606,091
5,606,191
Is this a bug in the Mac OS X 10.6 C++ std API?
The following code won't compile on Mac OS X 10.6; it gives an error in stl_algobase.h following a list of "instantiated from [...]" messages. #include <vector> int main( void ) { std::vector<int*> *v = new std::vector<int*>( 1, NULL ); return 0; } In order to make it compile, I have to place an explicit...
What's happening is that the compiler has to select between one of the vector constructor overloads that allows more than one argument: explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator()); template <class InputIterator> vector(InputIterator first, InputIterator last, cons...
5,606,657
5,607,660
C++0x concurrent synchronizes, is the fence needed
I've recently asked a few questions about atomics and C++0x, and I'd like to ensure I understand the ordering semantics before I convert any code. Let's say we have this pre-0x code: atomic_int a = 0; some_struct b; Thread A: b = something; atomic_store_fence(); a = 1; Thread B: if( a == 1 ) { atomic_load_fence(); ...
Yes, your understanding is correct, and yes the final listing is a reasonable implementation. Note that ATOMIC_VAR_INIT is primarily provided for compatibility with C1X, in C++0x you can just write: std::atomic<int> a(0);
5,606,669
5,606,681
C++ - Casting void pointer
Does C++ throw runtime exceptions when you try to cast a void* to something that it isn't? class Sheep { public: Sheep() { } ~Sheep() { } void Bah() { // Print Bah! } }; class Unicorn { Unicorn() { } ~Unicorn() { } void Stab(Sheep* s) { s->Bah(); } }; int m...
Does C++ throw runtime exceptions when you try to cast a void* to something that it isn't? No, it doesn't. The behavior of your program is undefined: anything could happen. The program might appear to work most of the time, it might crash at any point, or something worse might happen. void* should be avoided in all...
5,606,712
5,606,731
What is the expected behaviour of initialization using polymorphism in C++?
This should be a simple 100-level question, but I'm seeing something I don't expect in my project, and web searches have failed me, so I thought I'd ask here. Suppose I have the following C++ code: class BaseClass { public: BaseClass() { this->Initialize(); } int foo() { return this->foo_; } protect...
GetInitialValue() isn't virtual so there isn't dynamic dispatch anyway. In your situation, the expected value of foo() would be 1, as the value of _foo is set in the BaseClass constructor. The derived class's version isn't called as the BaseClass constructor is called first, and the DerivedClass members haven't been in...
5,606,750
5,606,803
Deletion of pointer to incomplete type and smart pointers
When trying to use an auto_ptr with a type that was declared with forward-declaration, like this: class A; ... std::auto_ptr<A> a; the destructor of A is not called (apparently, because auto_ptr internally deletes the underlying pointer and the destructor for an incomplete type cannot be called). However, the same co...
A shared_ptr can be declared with an incomplete type, yes. The type does not need to be complete until you initialize or reset it. When you initialize or reset a shared_ptr to point to a new object, it creates a "deleter" that can be used to destroy the object. For example, consider the following: // somewhere where ...
5,606,764
5,606,793
My class book says that arrays are set with const variables. What are some problems I could encounter when I use non const variables?
The C++ book I'm reading tells us that arrays are to be set with constant variables, but I wanted to let user input instruct the size of the array, and it worked. Are there are problems I should worry about.
How did you declare the array? You can create an array with a size based on a variable if you declare it this way: int size; cin >> size; // (assert size is > 0 and < some really big number here) int* myarray = new int[size]; // Do stuff with it here... delete [] myarray; // Don't forget this. and that will work just...
5,606,973
5,607,206
Understanding Iterators in the STL
What exactly are iterators in the C++ STL? In my case, I'm using a list, and I don't understand why you have to make an iterator std::list <int>::const_iterator iElementLocator; to display contents of the list by the derefrence operator: cout << *iElementLocator; after assigning it to maybe list.begin(). Please explai...
There are three building blocks in the STL: Containers Algorithms Iterators At the conceptual level containers hold data. That by itself isn't very useful, because you want to do something with the data; you want to operate on it, manipulate it, query it, play with it. Algorithms do exactly that. But algorithms don't...
5,607,011
5,609,397
QtCreator and signals and slots
In the QtCreator change signals/slots context menu, I can't insert neither signals nor slots that have parameterized arguments such as: QList<QString>, etc. or even references only regular types (int, QSring, etc.) Why?
When you connect a signal to a socket you use MetaType system of QObject: connect(sender, SIGNAL(updated(QList<MyClass>), receiver, SLOT(list_updated(QList<MyClass>)) The parameter of the signal and slot is of "QList<MyClass>" metatype. Since it is custom metatype, Qt library has no knowledge of underlying implementati...
5,607,085
5,607,602
How to replace all occurrences of one character with two characters using std::string?
Is there a nice simple way to replace all occurrences of "/" in a std::string with "\/" to escape all the slashes in a std::string?
Probably the simplest way to get this done is with boost string algorithms library. boost::replace_all(myString, "/", "\\/"); std::string result = boost::replace_all_copy(myString, "/", "\\/");
5,607,157
5,607,184
What exactly is a critical section?
Just want a little clarity on the this. Imagine I use the windows api of EnterCriticalSection. I call all of them with EnterCriticalSection(&criticalsection); This is the thread function that is multi threaded void thread (){ //enter critical section (part 1) data //leave critical section ///more data 1 //entercriti...
Critical section is a code chunk. If any thread entered it, no other thread can enter until it's free. If 1 and 2 are different critical sections (i.e. handled by a different semaphore), someone can enter 2 if 1 is occupied.
5,607,166
5,607,227
C++ function calling
I have a task: Fix wrong calls with ::, delete unfixable constructions int x = 4; class A{ int x; public: A(int n = 1); virtual int f(int a=0, int b=0); }; class B{ int x; public: B(int n = 2); int f(int a = 0); }; class C: public A, public B{ int x; public: C(int n=3); int f(in...
Overload resolution is not applied across different class scopes (§7.4). In particular, ambiguities between functions from different base classes are not resolved based on argument types. (Stroustrup, The C++ Programming Language, 15.2.2) Thus, compiler searches method by name first in "this" class, then recoursively i...
5,607,253
5,634,235
Syntactic sugar in C/C++
I have been looking into Ruby and find its keywords "until" and "unless" very interesting. So I thought what was a good way to add similar keywords into C/C++. This is what I came up with: #define until(x) while(!(x)) #define unless(x) if(!(x)) I am looking for some suggestions on this. Can anyone suggest a bette...
The way you did it seems to me the correct way to do it, if you're going to do it at all. Because the expansion of the macro is so similar to what you'd expect[1], I think it's valid to make the macro look like syntax (), rather than the usually recommended SCARY_UPPERCASE_MACROS() which are used to show that this code...
5,607,258
5,612,817
GTKmm books for complete beginner? Do I need to learn GTK+ before GTKmm?
I am familiar with C++ & OOP. I really want to develop a GUI for my program running on Linux using GTKmm. However, I could not find any good book or tutorial for GTKmm. I have never done any GUI programming before. I did read the gtkmm tutorial on GTKmm homepage http://www.gtkmm.org/en/ but I couldn't understand the ...
If you are focused on C++, I would stick with GTKmm and not bother with GTK+ C API for now. It's different enough and will probably just confuse you, especially if you do not have a strong C background. Unfortunately, the 3rd-party documentation of GTKmm is a little lacking. Their tutorial book though I think is top-...
5,607,314
5,692,737
Why does std::tr1::function work with Objective-C Blocks?
I was pretty surprised when I found that the following code actually works: std::vector<int> list /*= ...*/; std::tr1::function<void(int)> func = ^(int i) { return i + 1; }; std::for_each(list.begin(), list.end(), func); Seems like std::tr1::function is capable of being constructed from an Objective-C block, but I'...
Update: I was wrong, here's why it really works std::tr1::function's template parameter simply defines the signature of the resulting function object, not the type it actually wraps. Thus, the wrapped object only needs to offer an operator() with matching signature. Block references, like function pointers, have such a...
5,607,570
5,607,644
global variable defined in a dll and global variable of the host software
If I have a global variable defined in a DLL that my application load, is this variable is located at the same memory region that my others global variable defined in my application (so not directly in the DLL) ?
Global data loaded as part of the EXE and global data loaded as part of the DLL both reside in the virtual memory space of the same process, though in different areas corresponding to the segments defined in those EXE and DLL files. Since they are in the same virtual memory space, code in the DLL can use a pointer to ...
5,607,589
5,607,650
Right way to split an std::string into a vector<string>
What is the right way to split a string into a vector of strings? Delimiter is space or comma.
For space separated strings, then you can do this: std::string s = "What is the right way to split a string into a vector of strings"; std::stringstream ss(s); std::istream_iterator<std::string> begin(ss); std::istream_iterator<std::string> end; std::vector<std::string> vstrings(begin, end); std::copy(vstrings.begin(),...
5,607,613
5,607,659
G++ compiler doesn't recognize the enum type in C++
I tried to use enumerated type and template class, but i have no idea why the following code doesn't work: #include <stdio.h> #include <string.h> class Multilist { //TYPE DEFINITION struct mlNode; //forward declarations struct dlNode; template <class T> struct mlCat; typedef c...
You need to put those constructor calls in the constructor of Multilist: Multilist(...) : catId(ID), catOccupation(OCCUPATION), ... and remove them from the declarations. Your current usage looks like you are trying to declare functions returning mlCat<> thus ID et. al are being interpreted as the types of the argume...
5,607,630
5,607,702
C++ pure virtual method memory management question
I have a base class (AClass here) that has a protected resource (str here) that get's free'd in the AClass destructor. Derived BClass has a pure virtual Init method. Derived CClass implements Init which allocates some memory for the protected resource. Valgrind is saying that I have 3 allocs and 2 frees. Honestly, I on...
When you construct and then Init an instance of your CClass, the str pointer is first assigned a pointer from the malloc call in the AClass default constructor, and then later assigned a pointer from the malloc call in CClass::Init. The memory allocated in the AClass default constructor is never freed, and the pointer...
5,607,690
5,607,753
How does getline() work?
I have this piece of code that I use to load a linked list from a binary or a text file .. It works fine for text files but it always loads an extra line in the binary case , So I need to know how getline works: while(1) { if(!file.good()) break; getline(file,line); student.name=line; ge...
it always loads an extra line Of course: you are inserting what you have read without verifying that it was read successfully. You need to move your file.good() test after the reading attempt. Furthermore, there’s no need to test for good explicitly, the result of getline already gives you the status. The canonical w...
5,607,849
5,607,917
How to simulate a key press in C++
I was wondering how can I simulate a key depression in C++. Such as having code that when I run the program it presses the letter "W" key. I don't want to be displaying it in a console window I just want it to display the "W" key every time I click on a text field. Thanks! Note: I am not trying to make a spammer.
It looks like you want to use either SendInput() or keybd_event() (which is an older way of doing the same thing).
5,607,946
5,607,973
"Bresenham's" circle algorithm filling question
I've implemented "Bresenham's" (midpoint) algorithm to plot circles, and everything went well (C++ and OpenGL). I am wondering now if it is possible to use the same algorithm to fill the circles? Take the following few circles for example: http://imgur.com/S0Qy6 which are plotted with the following algorithm: void circ...
I'm not certain, but from squinting at your algorithm, I was expecting the last line to look more like plotLine(Point(p.x+x, p.y+x), Point(p.x+x, p.y+y)); (that is, start on a northeast 45 degree line from p.x, then go up to the point on the circle that you just drew).
5,608,005
5,608,399
Libraries for Algorithms
Are there any libraries/sdk/etc that 'allow' to use algorithms in your programs without any difficulty? The following code may describe my question better(I need something like this): algorithm* a = new search_algorithm("binary_search"); a->set_data("some text to be searched"); search_result_t r = a->search("this_te...
You've 'heard' of Boost and STL_, so I assume you've heard of boyer-moore, min spanning tree, Brent's algorithm What is it, exactly, that you are missing?
5,608,122
5,608,263
Boost serialize only first character of std::wstring
I'm using boost to serialize with the text archive an std::wstring variable. If I switch to std::string it works very well but when I use wstring I get only one character serialized. Why? std::wstring text; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & text; } ... std::os...
You are trying to serialize a wide character string with a narrow character archive. This causes the byte sequence comprising your wide character string to be interpreted as a sequence of narrow characters. If you take into account that ASCII characters take up only one of the bytes of the corresponding wide character ...
5,608,188
5,608,214
C++ templates and friend declaration
Can someone tell me whats wrong with my code. I'm guessing that I didn't overload << correctly, but I'm not sure how to fix it. The below code implements a simple Stack container. It fails at cout << si; update: Made suggested changes, still not compiling. update2: Got it! Thanks! #include <iostream> using namespace st...
template <typename T, int N> ostream& operator << (ostream& os, const Stack<T> &stack) The problem with this template is that the parameter N cannot be inferred from either of the function arguments because you are using the default template argument for the Stack argument. Looking at your implementation, you almost c...
5,608,199
5,608,244
new in one thread and delete in another, not allowed?
Im reading data from a com-port. Since I don't know when data is coming, I'm reading continuously in a thread. When i have read enough bytes, I let the main thread know this by posting a message with a pointer to the string: msg[i] = '\0'; completeMsg = new char[i]; strcpy(completeMsg, msg); PostMessage(hDlg, BT_MSG, N...
You should be able to use new in one thread and delete in another, provided you link against your compiler's multi-threaded runtime library. However, it looks like you actually have a buffer overrun. You are null-terminating msg with msg[i]=0, but only allocate i bytes --- you probably need new char[i+1].
5,608,556
5,608,575
Assignment operator - Self-assignment
Does the compiler generated assignment operator guard against self assignment? class T { int x; public: T(int X = 0): x(X) {} }; int main() { T a(1); a = a; } Do I always need to protect against self-assignment even when the class members aren't of pointer type?
Does the compiler generated assignment operator guard against self assignment? No, it does not. It merely performs a member-wise copy, where each member is copied by its own assignment operator (which may also be programmer-declared or compiler-generated). Do I always need to protect against self-assignment even whe...
5,608,751
5,608,786
simple program wont compile
Please take a look at my code. The error I get in Visual Studio is error LNK2019: unresolved external symbol "public: int __thiscall Employee::getId(void)" (?getId@Employee@@QAEHXZ) referenced in function _main Employee.h #ifndef EMPLOYEES #define EMPLOYEES #include <string> #include <iostream> using namespace std; ...
Looks like you forgot to link the two files together. Make sure that you're linking Employee.cpp and main.cpp files together. Are they added to the same VS project? EDIT: check out this link. It's outdated, but looks like you did not make a project that contains all the files. They should be linked automagically.
5,608,782
5,610,389
Best way to deal with child to parent mouse and keyboard events in a gui?
For my Gui I want to use the following system: The way it works is that, if the widget under the mouse does not consume a mouse or kb event, it is passed to that widget's parent until it is consumed or the desktop is reached. Just one thing puzzles me about it. Does that mean if a Button, for whatever reason has a Labe...
If the label is a child widget, then yes, the label will attempt to eat the event, fail (as usually the label doesn't have a handler method) and thus pass the event back up to the button. Chances are the easiest way to do this is to derive a subclass of the Label class, and override the handle function (assuming this i...
5,608,815
5,608,867
Printing values through pointers
I have a class Vertex and a class Graph to draw a graph. I wish to store few vertices i.e. objects of Vertex Class in the Vector of type Vertex, but due to few errors I wasn't able to store the vertex objects directly, so I am storing the references of the objects in vectors. But while displaying I wish to display the ...
From what I can see, in the first for loop, you're not getting the actual value from "g1.Vertice1[i]" but trying to print the pointer. The type of Vertice1 is vector<Vertex<VertexType, EdgeType>*> (a vector of pointers to Vertex objects,) so you need to change the line so that it uses the -> operator to dereference the...
5,608,834
5,608,859
Manually sorting vector<int> in C++
I am currently looking into how Vectors work in C++. I have read and understand their functionality pretty well. I'm looking at different ways of sorting a vector object with 10,000 ints, I've used the std::sort method, and a shell sort. I noticed that a shell sort for a vector is slower than sorting a simple C style a...
Try the quickselect or quicksort algorithms (very similar but depends on what you need). In any case, these are just relatively simple and popular algorithms - more importantly, in practice they are fast (although they do have bad worst cases). Regards, Dennis M.
5,609,096
5,609,194
send message to all clients
To learn how to use sockets, I've been working on a simple command-line chat program in OS X. My goal of the program is to have it work so when one client sends a message, the server relays the message back to all of the clients. However, when testing this, the server will send messages from the newer clients to the ...
When you fork a process, you get a whole new copy if its data. Specifically, each server process has its own copy of connectedClients, which has the value of the parent process at the moment of the fork. If the server parent process later updates connectedClients, the then-existing server child processes will never kno...
5,609,099
5,609,824
How to show terminal in linux application?
I was wondering if you could have it so when you go and click on a program in linux it always automatically brings up the command line for the information being displayed or if I decided to use ncurses for an interface. If so is this a system specific call or can you do this with ncurses? Because half of my program is ...
Yes, just invoke a terminal with your app in it. For example: rxvt -e myapp Starts a terminal running your app. You could also use xterm. If you want to use wide chars/unicode I recommend rxvt-unicode. You can put this in a .desktop file with an icon defined there, and then that will be placed in the system menu.
5,609,157
5,609,186
How to implement a minimum heap sort to find the kth smallest element?
I've been implementing selection sort problems for class and one of the assignments is to find the kth smallest element in the array using a minimum heap. I know the procedure is: heapify the array delete the minimum (root) k times return kth smallest element in the group I don't have any problems creating a minimum ...
The only array index which is meaningful to the user is zero, which is the minimum element. So, after removing k elements, the k'th smallest element will be at zero. Probably you should destroy the heap and return the value rather than asking the user to concern themself with the heap itself… but I don't know the detai...
5,609,293
5,610,246
Input Box in an MFC CWinApp
I want to use a simple input box in vc++ mfc. I did created a dialog called IDD_DIALOG1, and added a text box. I added a public variable for the input box and created a class call CInputDlg. Now I use the following code but I face with error: CInputDlg dialog; if (dialog.DoModal() == IDOK) { m[nodeTemp][i] = weigh...
At the top of the file containing this code (it looks like you've named it shortest pathdlg.cpp): CInputDlg dialog; if (dialog.DoModal() == IDOK) { m[nodeTemp][i] = weight; } You need to add an #include statement that tells the compiler you'll be using things defined in a different source code file. In this case,...
5,609,364
5,609,720
Return value of static variable from inline function
static inline JGPlatformInfo* currentPlatform(){ static JGPlatformInfo* platform = nil; if (platform == nil){ JGPlatformInfo info = supportedPlatform(); platform = &info; } return platform; } I am getting inconsistent results with this code (C family) The value of platform changes...
Variables you defined are always temporary. That means when you leave scope your variable is going to get destroyed and the pointer to it will be invalid (or worse: it will point to a valid location that it shouldn't point to). This is where dynamic allocation comes into hand. Here's how I would achieve the same effect...
5,609,413
5,609,456
Class: Object oriented paradigm had always confused me
Can somebody please explain me clearly by using some nice examples how c++ class is useful and why it is a good programming practice. I read a lot about class, did some programming in c++ using some classes but still I couldn't be clear why class are needed and how would they make the code more robust and readable. Th...
When you type a script or 20 lines of code or 100 lines of code it's no big deal. When you get to millions, you start to need a way to actually visualize your code. You need to be able to talk of different sections and how they interact. When you look at a long procedure, how is it organized? When you have 20 functio...
5,609,475
5,609,480
strange const correctness error
I have a header file that contains a class. Within that class, I have a function like so: class Definition { public: int GetID() { return Id; } //Other methods/variables private: int Id; } When I attemped to get that ID as so: for (std::map<Definition, std::vector<bool> >::iterator mapit = DefUseMap....
Declare the getID() method const: int getId() const { return Id; } Then the method can be called by a const reference, which is what operator<<() is being passed.
5,609,502
5,609,853
Fortran accepting string(?) from C
I feel like this should be an easy question, but I can't get it to work. I have some Fortran code that takes an input like: SUBROUTINE TRACE(X,Y,NAME,XX,YY) EXTERNAL NAME CALL NAME(X,Y,XX,YY) and I'm trying to pass in a name from C++ in the form: float x,y,xx,yy; char * name="IGRF"; trace_(&x,&y,nam...
So one advantage of Fortran2003 and later is that C interoperability is defined into the standard; it's a bit of a PITA to use, but once it's done, it's guaranteed to work across platforms and compilers. So here's cprogram.c, calling a Fortran routine getstring: #include <stdio.h> int main(int argc, char **argv) { ...
5,609,789
5,609,796
What is '~' used for in C++?
Possible Duplicate: In c++ what does a tilde “~” before a function name signify? What is the difference between the line with the ~ and the other line? public: myClass() {}; ~myClass() {};
myClass(){} is called constructor and ~myClass(){} is called destructor! Constructor is invoked when an object is created, and destructor is invoked when an object is destroyed. myClass *pObj = new myClass(); //constructor is invoked; //work with pObj; delete pObj; //destructor is invoked; That is an example when yo...
5,609,791
5,609,836
C++ Assigns Value to Two Strings At Once
unsigned short n = 0; while (!in.eof()) { in >> opString; //Read in string from file //Read the string from file character by character for (int i = 0; i < opString.size(); i++) { if (!op1b) //If we do not yet know our first operand (op1b = false, b stands fo...
Next time post complete code (with all declration). op1 and op2 are std::string? You try to write characters in op1 and op2 but you haven't allocated any space, i.e. you should either op1.resize(SOME_SIZE) before the loop or use std::string::push_back to append chars to the operands.
5,609,915
5,609,963
Best practice for passing primitive data type in C++ function
I'm writing a function for an avr chip to deserialize a byte stream to primitive types. I'd like to do it in as generic a way as possible and was wondering what the best practice would be to determine the type to deserialize. Ideas I have so far, include: Choice A: // Just write a function for each type double deserial...
For starters, C and D are invalid options because types are not valid function arguments; might as well rule them out right now. Choice B seems like the clear winner here, assuming you aren't concerned about byte ordering or other potential caveats of using a union as you are (it doesn't seem like you would be given th...
5,610,075
5,610,466
Taking a JPEG-encoded screenshot to a buffer using GDI+ and C++
I've adapted this code from another article here on SO. It takes a screenshot of the desktop and writes it to a file named "test.jpg." I'm interested in saving the JPEG data directly to a buffer to be sent over the network. I'm pretty sure GdipSaveImageToStream is what I need, but I can't figure out how it works. The G...
Short answer: Use the IStream version of Gdiplus::Image::Save. Use CreateHStreamOnGlobal to make a temporary IStream that you can convert back to a buffer; Long winded version with code sample. Replace this line: iRes = (pScreenShot->Save(lpszFilename, &imageCLSID, &encoderParams) == Ok); With this block of code: //...
5,610,135
5,610,164
With virtual destructors, do I need to explicitly declare a virtual destructor for each subclass?
I've got a scenario where I'm writing somewhat deep object oriented code, with multiple layers of abstract base classes, and I'm wondering if I have to explicitly declare a destructor for each one. Will the compiler generate a default one that's already virtual, or will I have to tell it to?
The default destructor is not virtual. If you declare the destructor of your base class as virtual, the destructors of the subclasses will be overrides, and thus also be virtual even without explicitly declaring them to be. The GNU GCC compiler even gives a warning if you have a class hierarchy and your base class doe...
5,610,215
5,610,232
What are the requirements on type for this template function
I am looking at C++ code that looks like this : template<class A> bool foo(int A::*) { /*blah*/ } What is the int A::* construct? What requirement does it impose on the type A? Thanks a lot!!
int A::* is a pointer to an int data member of type A. E.g., given the types: struct Foo { int i; }; struct Bar { double d; }; int Foo::* is a pointer to an int data member of type Foo, whose only valid values are null and the address of Foo::i int Bar::* is a pointer to an int data member of type Bar, whose only val...
5,610,221
5,610,252
How can I conceptualize an array with more than three dimensions?
I just learned about arrays but can't conceptualize arrays with more than three dimensions.
Imagine the following: Letters on the line of a book Lines on a page of a book Pages of the book Books in a bookshelf A room full of bookshelves House full of rooms A street with a number of houses A town with streets A Country with towns A planet with countries A universe full of planets And finally, a big array of u...
5,610,298
5,610,311
Why does int pointer '++' increment by 4 rather than 1?
Value of a pointer is address of a variable. Why value of an int pointer increased by 4-bytes after the int pointer increased by 1. In my opinion, I think value of pointer(address of variable) only increase by 1-byte after pointer increment. Test code: int a = 1, *ptr; ptr = &a; printf("%p\n", ptr); ptr++; printf("%p\n...
When you increment a T*, it moves sizeof(T) bytes.† This is because it doesn't make sense to move any other value: if I'm pointing at an int that's 4 bytes in size, for example, what would incrementing less than 4 leave me with? A partial int mixed with some other data: nonsensical. Consider this in memory: [↓ ...
5,610,527
5,610,531
boost Shared_pointer NULL
I'm using reset() as a default value for my shared_pointer (equivalent to a NULL). But how do I check if the shared_pointer is NULL? Will this return the right value ? boost::shared_ptr<Blah> blah; blah.reset() if (blah == NULL) { //Does this check if the object was reset() ? }
Use: if (!blah) { //This checks if the object was reset() or never initialized }
5,610,562
5,610,611
Multimap and shared_ptr
I want to sort my objects in boost::multi_map refer to some index. But I'm storing not pure objects, but wrapped into boost::shared_ptr. Here is the code: typedef boost::multi_index_container<boost::shared_ptr<Object>, boost::multi_index::indexed_by< boost::multi_index:: ordered_non_unique< ...
Change boost::multi_index::mem_fun<boost::shared_ptr<Object>, int, &boost::shared_ptr<Object>::getIndex> to boost::multi_index::mem_fun<Object, int, &Object::getIndex> According to the documentation it should work.
5,610,629
5,610,655
Difference between default-initialize and value-initialize?
Possible Duplicate: What do the following phrases mean in C++: zero-, default- and value-initialization? I was reading this answer, so I came across the second word : value-initialize. Initially I thought this is same as default-initialize but the context hints me that I'm wrong. So my question is : What is the dif...
According to the standard (8.5/4,5): To default-initialize an object of type T means: — if T is a non-POD class type the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); — if T is an array type, each element is default-initialized...
5,610,702
5,610,763
C++: Is "Virtual" inherited to all descendants
Assume the following simple case (notice the location of virtual) class A { virtual void func(); }; class B : public A { void func(); }; class C : public B { void func(); }; Would the following call call B::func() or C::func()? B* ptr_b = new C(); ptr_b->func();
Examples using pointers as well as reference. Using pointer B *pB = new C(); pB->func(); //calls C::func() A *pA = new C(); pA->func(); //calls C::func() Using reference. Note the last call: the most important call. C c; B & b = c; b.func(); //calls C::func() //IMPORTANT - using reference! A & a = b; a.func(); //...
5,610,714
5,610,740
Problem with showing my packets in console with ACE
for Debug reasons i want to show my outgoing packets in Console. The packets arrive at the server correctly btw. But if i want them to show in Console before sending, then it is showing just nothing: ACE_Message_Block *m_Header; ... size_t send_len = m_Header->length(); // Size of the Message Block c...
Likely the data you send contains 0's - and you'll need to append a newline as well. for (size_t i = 0; i < send_len; ++i) { if (output[i]<32) { printf("\\x%02hhx", (unsigned char) output[i]); } else { printf("%c", output[i]); } } printf("\n");
5,610,774
5,611,721
Decode JPEG to char*
Please help to solve this small problem: I try to decode incoming jpg data by OPENCV: cv::Mat video_frame = cv::imdecode(cv::Mat(buffer), -1); char* drawingData=??????; I can draw "drawingData" on the screen mannually if it is RGB 24 bits format. So the problem is how could I get the the drawingData from this video_f...
Try something like this char* data = (char *)image->imageData;