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
540,140
540,159
What is the conventions for headers and cpp files in C++?
In C++, what is the convention for including headers for class files in the "main" file. e.g. myclass.h class MyClass { doSomething(); } myclass.cpp doSomething() { cout << "doing something"; } run.cpp #include "myclass.h" #include "myclass.cpp" etc.. Is this relatively standard?
You don't include the .cpp file, only the .h file. The function definitions in the .cpp will be compiled to .obj files, which will then be linked into the final binary. If you include the .cpp file in other .cpp files, you will get two different .obj files with the same funciton definition compiled, which will lead to ...
540,252
540,500
Can any IDE or framework help test new code quickly without having to run the whole application
I mainly develop in native C++ on Windows using Visual Studio. A lot of times, I find myself creating a new function/class or whatever, and I just want to test that piece of logic I just wrote, quickly. A lot of times, I have to run the entire application, which sometimes could take a while since there are many connect...
It's very easy to get started with static unit testing in C++ - three lines of code. VS is a bit poor in that you have to go through wizards to make a project to build and run the tests, so if you have a thousand classes you'd need a thousand projects. So for large projects on VS I've tended to organised the project i...
540,337
540,357
How to Overcome Errors Thrown by mmsystem.h
I am not able to get out of these simple bugs, but would be great full if some one could answer to weed out from these errors. I included windows.h and some other necessary headers but couldn't able get out of it. Snippet of errors: error C2146: syntax error : missing ';' before identifier 'MMVERSION' error C4430: mis...
Look in mmsystem.h, lines 112 and 113: #ifdef _WIN32 typedef UINT MMVERSION; /* major (high byte), minor (low byte) */ So be sure to include windows.h befor including mmsystem.h, and if it does not help, try #defineing _WIN32 manually.
540,515
540,624
Named constructor and inheritance
I'm working on C++ framework and would like to apply automatic memory management to a number of core classes. So far, I have the standard approach which is class Foo { public: static shared_ptr<Foo> init() { return shared_ptr<Foo>(new Foo); } ~Foo() { } protected: Foo() { } }; // Exam...
I don't understand what this achieves, you don't appear to be getting any extra memory management using this init function than by simply declaring a shared_ptr. int main( void ) { shared_ptr<foo> a = foo::init(); shared_ptr<foo> b( new foo ); } What's the difference. shared_ptr provides the memory management,...
540,666
540,682
Will the ".target-name" targets in make files always run?
I'm new to make and makefiles, so forgive me if this is very basic. I'm looking through some makefiles in my project and I'm seeing 2 types of targets -- targets that don't begin with a . character and targets that do. And from what I'm guessing, it seems like the ".target-name" targets are always executed, is my assum...
No. The targets with a dot are normally special meaning targets (i.e. their functioniality is builtin into make). One of them is .PHONY, this is the one that defines the targets which are always executed (that means, the commands in their rules are run unconditionally). But there are also others, like .DEFAULT for th...
540,721
544,287
compile directly from vim
I'd like to compile cpp file w/o turning off vi. I know the :!g++ file.cpp but I prefer :make so I added this line in .vimrc file au FileType C set makeprg=gcc\ % au FileType Cpp set makeprg=g++\ % but I keep getting "make: ***** No targets specified and no makefile found. Stop.** "message. can anyone tell me wha...
I should change C,Cpp into c,cpp, then it works fine. thank you all, especially Rob Wells, your answer helped me a lot. thank you.
540,748
540,850
void, VOID, C and C++
I have the following code: typedef void VOID; int f(void); int g(VOID); which compiles just fine in C (using gcc 4.3.2 on Fedora 10). The same code compiled as C++ gives me the following error: void.c:3: error: ‘<anonymous>’ has incomplete type void.c:3: error: invalid use of ‘VOID’ Now, this is something in external...
Yes, as far as i know the second declaration is invalid in C++ and C89, but it is valid in C99. From The C99 draft, TC2 (6.7.5.3/10): The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters. It's explicitly talking about the type "void", not t...
540,800
540,836
Runtime dependency for std::string concatenation
std::string sAttr(""); sAttr = sAttr+VAL_TAG_OPEN+sVal->c_str()+VAL_TAG_CLOSE; else where in the code I have defined const char VAL_TAG_OPEN[] = "<value>"; sVal is a variable that is retrieved off of a array of string pointers. This works fine in most of the system, windows and linux. However at a customer site, wh...
Why the ->c_str()? If sVal is a std::string, try removing this call. Remember that the order of evaluation is undefined, so you may end up adding pointers instead of concatenating strings, because VAL_TAG_OPEN, sVal->c_str() and VAL_TAG_CLOSE are all plain C strings. I suggest you use the addition assignment operator +...
540,822
540,864
Allocating memory for triple pointer
The function somefunction() takes a triple pointer as an argument. int somefunction(tchar ***returnErrors); How to allocate memory for the returnErrors parameter?
At a guess . . . You can think of returnErrors as a pointer to an array of strings. The first * imples pointer to array of tchar (or a single string of tchars) The second * imples a pointer to an array of strings. The last * is so you can change returnErrors and pass back the new memory. To delare memory for this (si...
540,920
540,946
Which version of safe_delete is better?
#define SAFE_DELETE(a) if( (a) != NULL ) delete (a); (a) = NULL; OR template<typename T> void safe_delete(T*& a) { delete a; a = NULL; } or any other better way
Clearly the function, for a simple reason. The macro evaluates its argument multiple times. This can have evil side effects. Also the function can be scoped. Nothing better than that :)
541,022
541,048
Stringstream extract integer
Why do I fail to extract an integer value into the Num variable? #include <sstream> #include <vector> #include <iostream> using namespace std; int main() { string Digits("1 2 3"); stringstream ss(Digits); string Temp; vector<string>Tokens; while(ss >> Temp) Tokens.push_back(Temp); ss...
When the stream extracts the last of the 3 digist "1 2 3" the eof state will be set. This is not cleared by the str() member,you need to do it yourself. Change your code to: ss.clear(); ss.str(Tokens[0]);
541,062
541,097
boost::asio::serial_port reading after reconnecting Device
I have a problem with the boost::asio::serial_port class reading from a GPS device (USB-Serial). Connecting the device and reading from it works fine, but when I disconnect and reconnect the device, read_some doesn't read any bytes from the port. As boost doesn't seam to detect that the serial port is gone ( is_open() ...
It's hard to say what is the exact reason in your case, but practice shows that you often need to disable RTS sensitivity on your serial port. RTS is a pin on real RS-232 interface that is on when a device on the other side is on. serial_port::read_some invokes underlying Windows API function that looks on this signal....
541,078
541,091
Catching c++ base exceptions
In my project we have a base exception. For handling showing error dialogs, log and such. Im looking for a way to handle all derived classes of that exception, I thought this would work: try { main_loop(); } catch (const MyExceptionBase* e) { handle_error(e); } As every child instance thrown could be represented b...
Just mix the two approaches: use the base class, and use a reference. try { main_loop(); } catch (const MyExceptionBase& e) { handle_error(e); } BTW C++ can catch pointers, if you throw them. It's not advisable though.
541,386
546,390
Why do profilers need administrative privs (on Windows)
I've been evaluating profilers and memory checking tools for native C++ programs on Windows and all of them want to be installed and run with administrator privileges. I rarely log in as admin on my machine. If I need to install something or do something that requires administrative privileges, I use runas and it works...
I've been reading about this and I'm slowly coming to the conclusion that profiler-like tools in general do not require administrative access, but stating that you require it is an easy way for the tool makers to avoid all problems related to insufficient privileges. So, I guess they are being lazy but also somewhat pr...
541,561
541,862
Using Boost Tokenizer escaped_list_separator with different parameters
Hello i been trying to get a tokenizer to work using the boost library tokenizer class. I found this tutorial on the boost documentation: http://www.boost.org/doc/libs/1 _36 _0/libs/tokenizer/escaped _list _separator.htm problem is i cant get the argument's to escaped _list _separator("","",""); but if i modify the boo...
try this: #include <iostream> #include <boost/tokenizer.hpp> #include <string> int main() { using namespace std; using namespace boost; string s = "exec script1 \"script argument number one\""; string separator1("");//dont let quoted arguments escape themselves string separator2(" ");//split on spa...
542,006
542,499
Replace C style comments by C++ style comments
How can I automatically replace all C style comments (/* comment */) by C++ style comments (// comment)? This has to be done automatically in several files. Any solution is okay, as long as it works.
This tool does the job: https://github.com/cenit/jburkardt/tree/master/recomment RECOMMENT is a C++ program which converts C style comments to C++ style comments. It also handles all the non-trivial cases mentioned by other people: This code incorporates suggestions and coding provided on 28 April 2005 by Steven Mar...
542,028
542,118
Does the termination condition of a 'for loop' refresh in VC++ 6?
for (int i = 0 ; i < stlVector.size() ; i++) { if (i == 10) { stlVector.erase(stlVector.begin() + 5 ) } } Does the termination condition part "stlVector.size()" take "stlVector.erase(...)" into consideration? In other word does stlVector.size() refresh for every loop iteration? I can't test it ri...
Just to be clear, don't think of it in terms of the loop refreshing anything. Every time the condition is checked (at the start of each time through the loop), the size() method is called on the stlVector variable, and the current size of the vector is returned. The erase() method reduces the size of the vector, so th...
543,306
543,367
Platform-independent GUID generation in C++?
What is the best way to programmatically generate a GUID or UUID in C++ without relying on a platform-specific tool? I am trying to make unique identifiers for objects in a simulation, but can't rely on Microsoft's implementation as the project is cross-platform. Notes: Since this is for a simulator, I don't really n...
If you can afford to use Boost, then there is a UUID library that should do the trick. It's very straightforward to use - check the documentation and this answer.
543,507
543,557
In the C++ Boost libraries, why is there a ".ipp" extension on some header files
In the C++ Boost libraries, why is there a ".ipp" extension on some header files? It seems like they are header files included by the ".hpp" file of the same name. Is this convention common outside of Boost? What is the justification for having a special file type?
Explanation from one of the template gurus: If you want to split up your template sources into interface and implementation (there are lots of good reasons to do that, including controlling instantiation), you can't very well use the same name (foo.hpp) twice, and foo.cpp wouldn't be appropriate for either one. ...
543,515
543,537
Structs vs classes in C++
When should someone use structs instead of classes or vice versa in C++? I find myself using structs when a full-blown class managing some information seems like overkill but want to indicate the information being contained are all related. I was wondering what are some good guidelines to be able to tell when one is ...
Technically, the only difference between the two is that structs are public: by default and classes are private: Other than that, there is no technical difference. struct vs class then becomes a purely expressive nuance of the language. Usually, you avoid putting complicated methods in a struct, and most of the time st...
543,697
543,762
#include all .cpp files into a single compilation unit?
I recently had cause to work with some Visual Studio C++ projects with the usual Debug and Release configurations, but also 'Release All' and 'Debug All', which I had never seen before. It turns out the author of the projects has a single ALL.cpp which #includes all other .cpp files. The *All configurations just build ...
It's referred to by some (and google-able) as a "Unity Build". It links insanely fast and compiles reasonably quickly as well. It's great for builds you don't need to iterate on, like a release build from a central server, but it isn't necessarily for incremental building. And it's a PITA to maintain. EDIT: here's the ...
543,812
545,515
Calculate SLOC GCC C/C++ Linux
We have a quite large (280 binaries) software project under Linux and currently it has a very dispersed code structure - that means one can't [work out] what code from the source tree is valid (builds to deployable binaries) and what is deprecated. But the Makefiles are good. We need to calculate C/C++ SLOC for entire ...
The first thing you want is an accurate list of what you actually compiled. You can achieve this by using a wrapper script instead of gcc. The second list you want is the list of files that were used for this. For this, consult the dependency list (as you said that was correct). (Seems you'd need make --print-data-bas...
544,079
544,107
How do I use glutBitmapString() in C++ to draw text to the screen?
I'm attempting to draw text to the screen using GLUT in 2d. I want to use glutBitmapString(), can someone show me a simple example of what you have to do to setup and properly use this method in C++ so I can draw an arbitrary string at an (X,Y) position? glutBitmapString(void *font, const unsigned char *string); I'm ...
You have to use glRasterPos to set the raster position before calling glutBitmapString(). Note that each call to glutBitmapString() advances the raster position, so several consecutive calls will print out the strings one after another. You can also set the text color by using glColor(). The set of available fonts a...
544,206
544,225
Is it possible (or ok) to have a std::list of std::list's?
I have a std::list of Points (that simply store an x, y). Each one of these points represents a polygon, which I later draw. class Point { public: int x, y; Point(int x1, int y1) { x = x1; y = y1; } }; std::list <Point> currentPolygon; I would like to have a list of these polygons (l...
You could use this: std::list< std::list<Point> > polygons; To make things easier, use typedefs. class Point { public: int x, y; Point(int x1, int y1) { x = x1; y = y1; } }; typedef std::list<Point> PolygonType; typedef std::list<PolygonType> PolygonsType;
544,397
544,412
Concat strings and numbers in C++?
I'm trying to concat "(" + mouseX + ", " + mouseY ")". However, mouseX and mouseY are ints, so I tried using a stringstream as follows: std::stringstream pos; pos << "(" << mouseX << ", " << mouseY << ")"; _glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str()); And it doesn't seem to work. I get the following error:...
glutBitmapString() expects a char* and you're sending it a string. use .c_str() on the string like so: _glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str().c_str());
544,462
544,488
Global variables and scope - C++
I am having small problem in making a global variable works. I am using Visual Studio 2008 and standard C++. I have two projects, one is a static library and second one is a test program which uses this library. I have a global variable in global.h like #ifndef GLOBAL_H #define GLOBAL_H #include <string> extern std...
Don't use global variables. Just don't. Much better, if you HAVE to have globally accessible data, is to use a global function which will return globalWord, like this: std::string globalWord() { static std::string word("Hi Mom"); return word; } This saves you from initialization order issues (read Effective C+...
544,842
544,847
Creating a type alias for a templated class
Instead of using std::vector<Object> ObjectArray; I would like it to be MyArray<Object> ObjectArray; with all the std::vector methods preserved. (like push_back(), reserve(), ...etc) However, using typedef std::vector MyArray; won't work. Should I use template instead? How?
What you would really want is a templated typedef. Unfortunately those are not supported in the current version of C++, but they will be added in C++0x. For now, here's a possible workaround: template<class T> struct My { typedef std::vector<T> Array; }; My<Object>::Array ObjectArray Whether or not that is better...
544,845
544,897
How am I accidentally overwriting when referencing these pointers?
Last question for tonight, I promise. These pointers are giving me a serious headache. I have a std::list<Point> called Polygon and a std::list of Polygons defined like: typedef std::list<Point> Polygon; typedef std::list<Polygon> PolygonList; // List of all our polygons PolygonList polygonList; I created the me...
Other answers have pointed out what caused the error. As a general advice I would suggest not using references except in function arguments. The semantics are confusing, also for someone that will try to read your code. Try rewriting to something like this (I didn't test the code): void deleteNearestPoint(int x, int y)...
544,946
1,403,433
Building a library across platforms without running all of the platforms
I have a small piece of code that works as a plugin for a larger graphics application. The development platform is Qt with c++ code. I've managed to build a .so, .dylib and .dll for linux, MacOS and Windows respectively, but to do so I had to have a machine running each operating system (in my case, running linux [ub...
Better late than never, I just came across IMCROSS It looks quite promising!
545,329
545,609
Why does StackWalk64 return always true?
I tried to make my program dump and save its stack trace when crashes. I installed my own win32 SE handler with _set_se_translator and tried to dump the stack trace with StackWalk64 and finally throw a C++ exception (which actually does the logging when caught). The code looks like this: ... _set_se_handlers(WIN32EXCEP...
This looks very similar to code I've got, and that does work. The only difference I can see is that my code uses ZeroMemory() to clear the STACKFRAME64 structure before populating any parts of it - this may be required.
545,394
545,464
Combining Predicates
Is there any way that you can combine predicates? Lets say I have something like this: class MatchBeginning : public binary_function<CStdString, CStdString, bool> { public: bool operator()(const CStdString &inputOne, const CStdString &inputTwo) const { return inputOne.substr(0, inputTwo.length()).com...
I can recommend boost.lambda for combining function-objects for such tasks. Although it is a bit heavyweight for such a simple problem. (edit) See the community wiki answer started by xhantt for a good example using STL. (old, deprecated, answer) You can write your own utility for this, similar: // here we define the...
545,504
545,902
How to change font/color on MFC dialog for Windows Mobile?
Does anyone know how to set font and color on a static text and other controls of MFC dialog for Windows Mobile? Where can I get the list of supported fonts? Thanks!
Colors are changed via SetBkColor and SetTextColor. Here is an example of enumerating fonts.
545,532
545,555
What's the simplest way to create an STL - identity map?
I'd like to initialize a map - object "id" with identities from 0 to n-1, i.e. id[0] = 0 id[1] = 1 . . id[n-1] = n-1 Is there a simple way - a one-liner, a method inside the map-object, simply something really simple - that does that?
You could use the template <class InputIterator> map(InputIterator f, InputIterator l, const key_compare& comp) form of the constructor, but you'd need to build an InputIterator that worked as a generator function over the range you want. That'd be a whole lot more typing than just using a for loop.
546,596
546,689
What is the best data structure for representing nodes in 3D space?
... and thanks for reading... I'm still learning the ropes so please be forgiving... ;-) I am writing a function that meshes a solid in space. The mesh is done by using objects of a "Node" class and each node is represented by: int id double p double r Initially I thought that a map would be the way to go: with a map...
A map<> won't work. C++ associative containers work on the basis of key equality, and comparing floating-point numbers for equality doesn't work at all well. It sounds like you need to find a node, given x and y. The best way will depend on what you're trying to accomplish. Are you trying to find the nearest node, g...
546,669
546,678
C++ code analysis tools
I'm currently in the process of learning C++, and because I'm still learning, I keep making mistakes. With a language as permissive as C++, it often takes a long time to figure out exactly what's wrong -- because the compiler lets me get away with a lot. I realize that this flexibility is one of C++'s major strengths, ...
Enable maximum compiler warnings (that's the -Wall option if you're using the Gnu compiler). 'Lint' is the archetypical static analysis tool. valgrind is a good run-time analyzer.
546,993
547,058
Problems with const set&. Compiler/STL bug or non-portable usage?
Are there any language lawyers in the house? Should the following code compile? include <set> bool fn( const std::set<int>& rSet ) { if ( rSet.find( 42 ) != rSet.end() ) return true; return false; } On one of the platforms (Sun Workshop) this does not compile. It reports that the find function returned an iterato...
It should compile. Set includes 2 find() functions and 2 end() functions (const and non-const versions). It sort of sounds like Sun's STL is broken somehow. Since you are passing in a const reference, the compiler should be able to select the correct find() and end() functions.
546,997
547,007
Use #ifdefs and #define to optionally turn a function call into a comment
Is it possible to do something like this #ifdef SOMETHING #define foo // #else #define foo MyFunction #endif The idea is that if SOMETHING is defined, then calls to foo(...) become comments (or something that doesn't get evaluated or compiled), otherwise it becomes a call to MyFunction. I've seen __noop used, but I do...
Try this: #ifdef SOMETHING #define foo(x) #else #define foo(x) MyFunction(x) #endif If your function has several arguments, then: #ifdef SOMETHING #define foo(x,y,z) #else #define foo(x,y,z) MyFunction(x,y,z) #endif If your function has a variable number of arguments, then your compiler may support so-called "variadi...
547,011
548,809
How do you use bitwise flags in C++?
As per this website, I wish to represent a Maze with a 2 dimensional array of 16 bit integers. Each 16 bit integer needs to hold the following information: Here's one way to do it (this is by no means the only way): a 12x16 maze grid can be represented as an array m[16][12] of 16-bit integers. Each array element would...
Use std::bitset    
547,214
547,264
winsock weirdness (c++)
I am trying to implement a function called "inet_pton" which will convert a string representation of an IPv4 or IPv6 (like "66.102.1.147" [google]) into binary network-byte ordered form. Here is the relevant part of my code: #if defined WIN32 int inet_pton (int af, const char *src, void *dst) { const void *data; ...
Well, for a start you're asking for a stream socket with UDP as a protocol and that just isn't going to happen. Try with: hints.ai_family = af; hints.ai_socktype = 0; hints.ai_protocol = 0; hints.ai_flags = AI_NUMERICHOST; and memset it to zero first as it has extra members that you're not setting... Also in my ...
547,290
547,439
Is the "empty base optimization" in GCC configurable?
Consider these types: struct A {}; struct B : A { int i; }; sizeof(A) > 0 as required by the standard. sizeof(B) should be 4 due to the empty base optimization. Yet on GCC 4.1.1 it's 5 (I'm using a pack of 1 in this area). And inconsistently - some of my files are getting it, some are not. Can't be sure what the d...
This always happens. I post immediately before I figure it out. Maybe the act of posting gets me thinking in a different way.. So in my question the sample was a little bit over-simplified. It's actually more like this: struct Base {}; struct C1 : Base { int i; } struct C2 : Base { C1 c; int i; } sizeof(C1) is correct...
547,758
547,770
Read data with varying formats in C++
I'm creating my first real binary parser (a tiff reader) and have a question regarding how to allocate memory. I want to create a struct within my TiffSpec class for the IFD entries. These entries will always be 12 bytes, but depending upon the type specified in that particular entry, the values at the end could be of ...
In C++ you should use a union. This is a mechanism by which you can define several, overlapping data types, possibly with a common header. See this article for how to use unions for exactly your problem -- a common header with different data underneath.
547,833
548,072
Concrete class specific methods
I have an interesting problem. Consider this class hierachy: class Base { public: virtual float GetMember( void ) const =0; virtual void SetMember( float p ) =0; }; class ConcreteFoo : public Base { public: ConcreteFoo( "foo specific stuff here" ); virtual float GetMember( void ) const; virtual void S...
The cast would be faster than most other solutions, however: in Base Class add: void passthru( const string &concreteClassName, const string &functionname, vector<string*> args ) { if( concreteClassName == className ) runPassThru( functionname, args ); } private: string className; map<string, int>...
548,751
548,859
Should I become proficient with STL libraries before learning BOOST alternatives?
Does it make sense to restrict yourself to the STL libraries when learning C++ and then tackle boost and its additions after you have become fairly proficient with vanilla C++? Or should you dive right into BOOST while learning C++?
The STL has some core concepts to it. Boost builds on and expands on them. If you understand them, then moving right on to Boost may be of use to you. If not, I would start with the STL. The distinction between the various container types (sequences like vector, list and deque, and associations like map, set and th...
548,819
548,858
How to determine a process "virtual size" (WinXP)?
I have a program that needs a lot of memory, and it crashes as soon as the 2GB virtual address space is reached. Sysinternals process explorer displays this as "virtual size" column. How can I determine this "virtual size" with C (or C++) code? Ok, I have to query a performance counter for "Virtual Bytes". Perfmon sh...
According to MSDN: Memory Performance Information PROCESS_MEMORY_COUNTERS_EX.PrivateUsage is the same as VM Size in Task Manager in Windows XP. GetProcessMemoryInfo should work: PROCESS_MEMORY_COUNTERS_EX pmcx = {}; pmcx.cb = sizeof(pmcx); GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_CO...
548,969
548,994
Using ": number" while declaring variables
If i declare an enum as follows: typedef enum A { a = 0x00000001, b = 0x00000002 } AObj; Now if i declare a variable of AObj as follows what does this mean? AObj myAObj : 2;
It is a way of specifying the number of bits used. That is 2 means 2 bits. Also note that this is only useful when used with other bit fields in the same struct as alignment and padding will cause the memory to be skipped.
549,031
549,089
How do you include images as resources in a C++ executable?
Is it possible include images (jpegs) as resources in a win32 c++ executable? If so how?
Here's the MSDN documentation about resource files. http://msdn.microsoft.com/en-us/library/aa380599(VS.85).aspx
549,206
549,210
Public boost::signal object
I make my boost::signals public because I'm lazy. class Button { public: signal<void()> clicked; }; int main() { Button btn; btn.clicked.connect(handleClick); } ... rather than encapsulating with a Button::OnClicked(boost::function<void()>). Is this going to come back and bite me?
It depends. It has bitten me before when I wanted to add some special logic each time an object connected to another object's signals. This is the most likely case to bite you. Also, it can make it difficult to keep track of exactly when other objects are connecting to any given object. I would say hide the connection...
549,249
591,068
Polymorphism across C++ and Ruby using SWIG
I use SWIG to wrap a Ruby script around a C++ library. In Ruby, I can inherit from a C++ class, but I cannot pass the resulting pointer to a C++ function in a polymorphic way. Here is a concrete example. The SWIG interface file defines base class Animal with virtual function sound(): [animals.i] %module(directors="...
I got a solution to my problem from Tobias Grimm at the swig-user mailing list. The first part of the problem is SWIG's misleading error message. The message seems to suggest that I pass the wrong type of pointer to my C++ function, but this is not the case. If you check the class of the exception in Ruby, it's Object...
549,849
549,857
Preventing Virtual Method Implementation in C++
I have the following class hierarchy in C++: class Base { virtual void apply() = 0; }; class Derived : public Base { virtual void apply() { // implementation here that uses derived_specialty } virtual void derived_specialty() = 0; }; class Implementation : public Derived { virtual voi...
You can kind of do it by composition: class Base { virtual void apply(); }; class Derived : public Base { class IImplementation { virtual void derived_specialty() = 0; }; IImplementation& m_implementation; Derived(IImplementation& implementation) : m_implementation(implementation...
549,983
550,137
Not necessary to export class with only virtual/inline functions?
In C++ on Win32: Suppose I have a DLL with a header file that declares a class. The DLL exports some means of obtaining a pointer/reference to an instance of that class, such as a factory function. Am I correct in believing that it is not necessary to mark that class as exported using __declspec if one is only going t...
Am I correct in believing that it is not necessary to mark that class as exported using __declspec if one is only going to call virtual or inline functions on its instances? Yes,this is correct, and that's what COM do, the DLL only expotys 4 methods, one of them returns to the class factory, which all its members are...
550,035
550,048
vector<string> or vector<char *>?
Question: What is the difference between: vector<string> and vector<char *>? How would I pass a value of data type: string to a function, that specifically accepts: const char *? For instance: vector<string> args(argv, argv + argc); vector<string>::iterator i; void foo (const char *); //*i I understand usi...
This really has nothing to do with vectors specifically. A char* is a pointer, which may or may not point to valid string data. A std::string is a string class, encapsulating all the required data that makes up a string, along with allocation and deallocation functionality. If you store std::string's in a vector, or an...
550,106
550,119
Debug-compiled executable: Why not abort gracefully on invalid write to NULL?
What I don't understand about C/C++ is: Yes, everyone uses it to get blazingly fast executables, so they compile with optimization turned on. But for compilation with debug information turned on, we don't care about speed. So why not include more information in that compile mode, for example detect some segfaults befo...
There are a few major problems with your suggestion: What conditions do you want the compiler to detect? On Linux/x86, unaligned access can cause SIGBUS and stack overflow can cause SIGSEGV, but in both cases it technically is possible to write the application to detect those conditions and fail "gracefully". NULL po...
550,189
550,206
Is it safe to `delete this`?
In my initial basic tests it is perfectly safe to do so. However, it has struck me that attempting to manipulate this later in a function that deletes this could be a runtime error. Is this true, and is it normally safe to delete this? or are there only certain cases wherein it is safe?
delete this is legal and does what you would expect: it calls your class's destructor and free the underlying memory. After delete this returns, your this pointer value does not change, so it is now a dangling pointer that should not be dereferenced. That includes implicit dereferencing using the class's member variabl...
550,219
550,224
Link error using templates
I converted a function to a template, and started getting this error. I must not be understanding a limitation of templates. Can someone tell me why this is broken? I am receiving this error: Undefined symbols: "bool foo<int>(int const&, int const&)", referenced from: _main in file1.o ld: symbol(s) not found ...
For the reason Uri gave, template methods are usually defined in the header file. Because yours is a function and not a method of a class, explicitly define it (in the header file which may be included by more than one CPP file) as static or inline. Put this in your foo.h template<class T> inline bool foo (const T& lef...
550,223
550,288
UPDATE: C++ Pointer Snippet
Greetings again, and thanks once more to all of you who provided answers to the first question. The following code is updated to include the two functions per the assignment. To see the original question, click here. I am pretty sure this fulfills the requirements of the assignment, but once again I would greatly appr...
The code looks good. However, there are some problems you may want to address, for us humans: Your function signatures (declarations) lack parameter names. More suitable: int** createArray(int rows, int columns); void deleteArray(int** array, int rows); Your function names aren't too descriptive as to what they re...
550,418
550,425
Designing a lazy vector: problem with const
I wrote a little "lazy vector" class (or, delayed vector) which is supposed to look like a std::vector and usable wherever a std::vector is used, but it loads its elements "lazily", i.e. it will load element n (and possibly a few more) from disk whenever someone accesses element n. (The reason is that in my app, not al...
You can either use mutable member data or const_cast in the implementation of your LazyVector class. Thus you can create the illusion of constness needed by your consuming class without actually being const.
550,428
550,431
An odd C++ error: test.cpp:15: error: passing ‘const *’ as ‘this’ argument of ‘*’ discards qualifiers
I'm having some trouble with a particular piece of code, if anyone can enlighten me on this matter it would be greatly appreciated, I've isolated the problem down in the following sample: #include <iostream> using namespace std; class testing{ int test(); int test1(const testing& test2); }; int testing::test()...
The problem is calling a non-const function test2.test() on a const object test2 from testing::test1. testing::test1 gets test2 as a parameter const testing &test2. So within testing::test1, test2const. Then in the first line of the function: test2.test() The testing::test function is called on test2. That function ...
550,451
550,457
Will new return NULL in any case?
I know that according to C++ standard in case the new fails to allocate memory it is supposed to throw std::bad_alloc exception. But I have heard that some compilers such as VC6 (or CRT implementation?) do not adhere to it. Is this true ? I am asking this because checking for NULL after each and every new statement mak...
VC6 was non-compliant by default in this regard. VC6's new returned 0 (or NULL). Here's Microsoft's KB Article on this issue along with their suggested workaround using a custom new handler: Operator new does not throw a bad_alloc exception on failure in Visual C++ If you have old code that was written for VC6 behav...
550,455
550,462
Compile error: Undefined symbols: "_main", referenced from: start in crt1.10.5.o
I have the following code: #include <iostream> using namespace std; class testing{ int test() const; int test1(const testing& test2); }; int testing::test() const{ return 1; } int testing::test1(const testing& test2){ test2.test(); return 1; } after compilation, it gives me the following error: Unde...
You have tried to link it already: g++ file.cpp That will not only compile it, but try to already create the executable. The linker then is unable to find the main function that it needs. Well, do it like this: g++ -c file.cpp g++ -c hasmain.cpp That will create two files file.o and hasmain.o, both only compiled so f...
550,548
550,564
Odd behavior with operator>= overloading
I'm having a strange behavior with an operator overloading in C++. I have a class, and I need to check if its contents are greater or equal to a long double. I overloaded the >= operator to make this check, my declaration is as follows: bool MyClass::operator>=(long double value) const; I have to say that I also have ...
2015 update: Or, if you want to keep conversion ability using the (double)obj syntax instead the obj.to_double() syntax, make the conversion function explicit by prefixing it with that keyword. You need an explicit cast then for the conversion to trigger. Personally, I prefer the .to_double syntax, unless the conversio...
550,686
550,690
How do I convert from a 32-bit int representing time in usec to a 32-bit int representing time as a binary fraction in secs?
POSIX uses struct timeval to represent time intervals. struct timeval { time_t tv_sec; unsigned tv_usec; }; GHS Integrity represents Time in the following manner, struct Time { time_t Seconds; unsigned Fraction; }; For example, 0.5sec is represented as 0x80000000 and 0.25sec is represented as 0x4000...
This is an unusual way to represent time. Anyway, there are two easy ways to do it either way if you have 64-bit integers or floating points (the former are more likely on an embedded system): /* assuming long is 64-bit and int is 32-bit or in general long twice the size of int: */ Fraction = (long) tv_usec * UINT_M...
550,797
551,247
Is there a better way to print a string with cout up to N characters?
-edit- I am sending binary and not a string. My test is using html pages so in this example i am only using a string but my question is about binary, vectors and debugging with ostream. I make this clears some confusion. I have the following code: cout << string(&v[0]).substr(0, len); Is there a better way to print th...
You can use the method ostream::write on the cout object: #include <iostream> #include <vector> using namespace std; int main() { vector<char> test; test.push_back('a'); test.push_back('b'); test.push_back('c'); cout.write(&test[0], 3); cout << endl; } Outputs: abc Since ostream::write returns an ostr...
550,859
550,862
Reference to value of STL map element?
Is it OK to pass to function a reference to the value of map element, and to modify it there? foo(string & s) { s = "xyz"; } map<int, string> m; m[1] = "abc"; foo(m[1]); // <-- Is it ok? Will m[1] be "xyz" after this call? Thank you.
The answer is Yes. (operator [] returns a reference)
551,069
551,124
Testing pointers for validity (C/C++)
Is there any way to determine (programatically, of course) if a given pointer is "valid"? Checking for NULL is easy, but what about things like 0x00001234? When trying to dereference this kind of pointer an exception/crash occurs. A cross-platform method is preferred, but platform-specific (for Windows and Linux) is al...
Update for clarification: The problem is not with stale, freed or uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash? Yo...
551,156
551,160
Compiler not creating templated ostream << operator
I have a class, defined in a head as: template <typename T> class MyClass { template <typename U> friend std::ostream& operator<<(std::ostream& output, const MyClass<U>& p); public: ... } In an implementation file, I have: template <typename U> std::ostream& operator<<(std::ostream& output, const MyClass<U...
In an implementation file, I have: That's the problem. You can't split template definitions between header and implementation files. Due to the nature of templates, C++ compilers are finicky here. Define all the code in the header to make it work. In fact, the problem here is that all template definitions must reside...
551,200
551,205
Microsoft Visual Studio (2008) - Filters in the Solution Explorer
In the Solution Explorer when working with C++ projects there is the standard filters of Header Files, Resource Files, and Source Files. What I'm wanting to accomplish is essentially Filters by folder. Lets say the structure of the files was like this: ../Folder1/Source1.cpp ../Folder1/Header1.h ../Folder1/Source2.cp...
You are free to manually create folders yourself and move the files around. I agree this is a much more convenient way to arrange files but AFAIK there is no way to make VS do this automatically.
551,226
551,275
Can`t really understand what the parameters for constructing tcp::resolver::query
I am starting Boost.Asio and trying to make examples given on official website work. here`s client code: using boost::asio::ip::tcp; int _tmain(int argc, _TCHAR* argv[]) { try { boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], "da...
You would run the program with the IP or Hostname of the server you want to connect to. tcp::resolver::query takes the host to resolve or the IP as the first parameter and the name of the service (as defined e.g. in /etc/services on Unix hosts) - you can also use a numeric service identifier (aka port number). It retur...
551,227
551,533
Deploying application with Python or another embedded scripting language
I'm thinking about using Python as an embedded scripting language in a hobby project written in C++. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this. Is it feasible to deploy a Python int...
Link your application to the python library (pythonXX.lib on Windows) and add the following to your main() function. Py_NoSiteFlag = 1; // Disable importing site.py Py_Initialize(); // Create a python interpreter Put the python standard library bits you need into a zip file (called pythonXX.zip) and place this and...
551,243
924,752
Symbian OS/C++ Descriptors Port?
Does anyone know if there's a working port of the Symbian OS C++ Descriptors functionality to other operating systems? I recall there being some code towards that here, although last time I tested it, it did not compile with G++ due to some missing/undefined types. Thanks in advance, Tyson
There's nothing inherently platform-specific about descriptors and you could trivially port them (i.e. re-compile them) to another platform from the Symbian source once it's open sourced. However, since some of the descriptor functions 'leave' you'd have to pull in the Symbian cleanup stack functionality too. Since th...
551,263
551,280
Method chaining + inheritance don't play well together?
Consider: // member data omitted for brevity // assume that "setAngle" needs to be implemented separately // in Label and Image, and that Button does need to inherit // Label, rather than, say, contain one (etc) struct Widget { Widget& move(Point newPos) { pos = newPos; return *this; } }; struct Label : Widget {...
For the second problem, making setAngle virtual should do the trick. For the first one, there are no easy solutions. Widget::move returns a Widget, which doesn't have a setText method. You could make a pure virtual setText method, but that'd be a pretty ugly solution. You could overload move() on the button class, but ...
551,595
551,620
Temp file that exists only in RAM?
I'm trying to write an encrpytion using the OTP method. In keeping with the security theories I need the plain text documents to be stored only in memory and never ever written to a physical drive. The tmpnam command appears to be what I need, but from what I can see it saves the file on the disk and not the RAM. Using...
The simple answer is: no, there is no platform independent way. Even keeping the data only in memory, it will still risk being swapped out to disk by the virtual memory manager. On Windows, you can use VirtualLock() to force the memory to stay in RAM. You can also use CryptProtectMemory() to prevent other processes fro...
552,131
552,143
How to read in specific sizes and store data of an unknown type in c++?
I'm trying to read data in from a binary file and then store in a data structure for later use. The issue is I don't want to have to identify exactly what type it is when I'm just reading it in and storing it. I just want to store the information regarding what type of data it is and how much data of this certain type ...
You could copy it to the known data structure which makes life easier later on: double x; memcpy (&x,memory,sizeof(double)); or you could just refer to it as a cast value: if (*((double*)(memory)) == 4.0) { // blah blah blah } I believe a char* is the best way to read it in, since the size of a char is guaranteed...
552,253
552,276
Efficient way of extracting specific numerical attributes from XML
The application I work uses XML for save/restore purposes. Here's an example snippet: <?xml version="1.0" standalone="yes"?> <itemSet> <item handle="2" attribute1="30" attribute2="blah"></item> <item handle="5" attribute1="27" attribute2="blahblah"></item> </itemSet> I want to be able to efficiently pre-process the X...
You are looking for a stream oriented XML parser that reads each node in your XML one at a a time rather then loading the whole thing into memory. One of the best known is the SAX - Simple API for XML Here's a good article describing why to use SAX and also specific of using SAX in C++. You can think of SAX as a par...
552,446
552,451
Importing a C# class library into Visual C++
I have a C# class library that contains methods that need to be used with an external application. Unfortunately this external application only supports external APIs in C/C++. Suppose I have a takeIntReturnDoubleArray method in this C# library that takes an integer and returns an array of doubles. All I need to do i...
You have two main options here: C++\CLI - this allows you to have both managed and unmanaged code in the same source file. The managed portion can then call the C# code. COM Interop - expose your .NET type as a COM interface and matching coclass which you can easily use from unmanaged C++.
552,509
552,557
cross compiling c++ to iphone arm
I've scanned over the (outdated) article that is the first hit on google about ARM cross-compiling. I've also seen the article about compiling OpenCV to the iPhone and the general cross compiling instructions there. My question is can I call the apparently already configured gcc/g++ in the iPhone developer package (whi...
If you're using the official SDK, compiling C++ for the iPhone is as simple as including cpp files in your project and hitting "build". Of course you can still go in and tweak the compiler switches - well, most of them. As for ncurses, I'm not sure why you'd want to use that - but the only limitation you should have is...
552,540
552,559
Why are some programs written in C++ windows-only and others are not?
That's something I've been wondering for a while now. Take Notepad++ for instace. Wikipedia tells me it was written in C++ and it's Windows-only. Now take PHP. Wikipedia tells me this is also written in C++, but that runs on other OS too. But I see more languages then just C++ for PHP... how is this done? Do they make ...
It depends whether you are using platform specific libraries or not. Notepad++ is a desktop application and it needs a GUI toolkit. Although there are cross-platform C++ libraries like Qt and wxWidgets, Notepad++ is probably using a Microsoft's specific technology. Thus it can't be ported in other platforms. PHP on the...
552,638
552,640
I've got a pointer to an object. How do I call a function that expects a reference?
I have a function which takes a reference to an object: void move(Ball& ball); I have another function calling 'move()' which has a pointer to ball: void foo(Ball* ball){ //call move() } How is foo() supposed to pass ball to move()? Should it be like: move(*ball); or: move(ball); or: move(&ball);
The first one, move(*ball). the second one, move(ball) tries to pass the pointer and the third one, move(&ball) tries to pass a pointer to a pointer.
552,822
553,647
Why is this code losing handles on Windows 7 Beta?
I'm looking for some random crashes in an old c++ application. Using sysinternals process explorer, I noticed the app losing handles, and extracted the exact situation, where the program is losing handles to a very short piece of code. DWORD WINAPI MyTestThread( void* PThread) { _endthreadex(0); return 0; } int WIN...
Check whether some DLL which is linked to your exe is doing something strange in its DLLMain in response to DLL_THREAD_ATTACH notifications.
552,854
553,491
How to use a BGL directed graph as an undirected one (for use in layout algorithm)?
I am working on a directed graph (actually a bidirectional one) with Boost.Graph. I'd like to use the layout algorithms that exist (either Kamada-Kawai or Fruchterman-Reingold) but they only accept undirected graphs as parameters. What is the simplest way to use these layout algorithms ? More generally, what's the righ...
Are you sure that Fruchterman-Reingold algorithm only accepts undirected graphs? I tried to run the little example from the Boost documentation using a bidirectional graph instead of an undirected one, and it compiled and ran just fine. To answer your question, I'm not sure there is any facilities built into the BGL t...
552,960
556,779
Disable IE script debugging via IE control
Bleh; Knowing how to ask the question is always the hardest so I explain a little more. I'm using CAxWindow to create an IE window internally and passing in the URL via the string class argument: CAxWindow wnd; m_hwndWebBrowser = wnd.Create(m_hWnd, rect, m_URI, WS_CHILD|WS_DISABLED, 0); It's part of an automated utili...
I found some projects on CodeProject that does something similar... http://www.codeproject.com/KB/shell/popupblocker.aspx?fid=15235&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=51&select=646577 http://www.codeproject.com/KB/shell/popupblocker2.aspx?df=100&forumid=15709&fr=51&select=548519#xx548519xx And also an MSD...
552,999
553,109
How to read input from a webcam in C++?
is it possible to read data from a generic webcam in C++ as you would from a stream object? Is there a common API or standard that works with all webcams? I'm talking about C++ in *nix environment. Thanks in advance.
For linux, V4L. AFAIR, BSD uses the same codebase. I do not know about the others...
553,503
555,180
Where can I find a flexible logging library for Windows Mobile?
Can anyone suggest any open and free library for logging on Windows Mobile application written in C++? It would be nice if it supports logging to files, syslog (would be nice) and logging level.
None that I know of. You will most likely have to look for source code available logging libraries. Windows Mobile will pretty much compile most win32 code with no or little changes, so any win32 logging library should work. Generally I build my own as I like fine gained control over my logging code.
553,543
553,559
Can I have nested try-catch blocks in C++?
Can I have nested try-catch blocks? For example: void f() { try { //Some code try { //Some code } catch(ExceptionA a) { //Some specific exception handling } //Some code } catch(...) { //Some exception...
Yes perfectly legal. Though it would be best to move inner ones into another method so it looks cleaner and your method(s) are smaller
553,682
553,869
When can I use a forward declaration?
I am looking for the definition of when I am allowed to do forward declaration of a class in another class's header file: Am I allowed to do it for a base class, for a class held as a member, for a class passed to member function by reference, etc. ?
Put yourself in the compiler's position: when you forward declare a type, all the compiler knows is that this type exists; it knows nothing about its size, members, or methods. This is why it's called an incomplete type. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would n...
553,846
553,878
Where is SetOaNoCache defined?
Attempting to disable BSTR caching: SetOaNoCache(); VC++ compiler build output: 'SetOaNoCache': identifier not found Don't want to use: OANOCACHE=1 Question: Where is SetOaNoCache defined - header file?
It is not defined in a header file, it is in OLEAUT32.dll. You can call it like this: typedef int (*SETOANOCACHE)(void); void DisableBSTRCache() { HINSTANCE hLib = LoadLibrary("OLEAUT32.DLL"); if (hLib != NULL) { SETOANOCACHE SetOaNoCache = (SETOANOCACHE)GetProcAddress(hLib, "SetOaNoCache"); ...
553,974
553,986
Why does (int)55 == 54 in C++?
So I'm learning C++. I've got my "C++ Programming Language" and "Effective C++" out and I'm running through Project Euler. Problem 1...dunzo. Problem 2...not so much. I'm working in VS2008 on a Win32 Console App. Whats the Sum of all even terms of the Fibonacci Sequence under 4 million? It wasn't working so I cut...
Casting to int truncates the number - same as if you'd called floor(currentFib). So even if currentFib is 54.999999... (a number so close to 55 that it will be rounded up when printed), (int)currentFib will produce 54.
554,063
554,134
How do I print a double value with full precision using cout?
In my earlier question I was printing a double using cout that got rounded when I wasn't expecting it. How can I make cout print a double using full precision?
You can set the precision directly on std::cout and use the std::fixed format specifier. double d = 3.14159265358979; cout.precision(17); cout << "Pi: " << fixed << d << endl; You can #include <limits> to get the maximum precision of a float or double. #include <limits> typedef std::numeric_limits< double > dbl; dou...
554,204
554,215
Where is Round() in C++?
Duplicate of: round() for float in C++ I'm using VS2008 and I've included math.h but I still can't find a round function. Does it exist? I'm seeing a bunch of "add 0.5 and cast to int" solutions on google. Is that the best practice?
You may use C++11's std::round(). If you are still stuck with older standards, you may use std::floor(), which always rounds to the lower number, and std::ceil(), which always rounds to the higher number. To get the normal rounding behaviour, you would indeed use floor(i + 0.5). This way will give you problems with neg...
554,476
554,575
Does this C++ class containing a variable size array use dynamic memory allocation?
Does doing something like this use dynamic memory allocation? template <class T, int _size> class CArray { public: ... private: T m_data[_size]; }; Can someone explain to me what's going on behind the scenes when I create the object? CArray<SomeObject, 32> myStupidArray;
As mentioned in the other answers, templates are evaluated at compile time. If you're interested you can have g++ spit out the class hierarchy where you can verify its size: template <class T, int _size> class CArray { public: private: T m_data[_size]; }; int main(int argc, char **argv) { CArray<int, 32> myStupidA...
554,551
623,199
Call function in c++ dll without header
I would like to call a method from an dll, but i don't have the source neither the header file. I tried to use the dumpbin /exports to see the name of the method, but i can found the methods signature? Is there any way to call this method? Thanks,
It is possible to figure out a C function signature by analysing beginnig of its disassembly. The function arguments will be on the stack and the function will do some "pops" to read them in reverse order. You will not find the argument names, but you should be able to find out their number and the types. Things may ge...
554,646
577,501
C++ serialization of complex data using Boost
I have a set of classes I wish to serialize the data from. There is a lot of data though, (we're talking a std::map with up to a million or more class instances). Not wishing to optimize my code too early, I thought I'd try a simple and clean XML implementation, so I used tinyXML to save the data out to XML, but it wa...
There are many advantages to boost.serialization. For instance, as you say, just including a method with a specified signature, allows the framework to serialize and deserialize your data. Also, boost.serialization includes serializers and readers for all the standard STL containers, so you don't have to bother if all ...
554,847
554,860
What is the best way to learn C++ if I have a bit of other programming experience?
Just would like some thoughts of what you think about my strategy to learn C++. While I understand that it takes years to master a programming language, I simply want to get to the point where I can be considered competent as quickly as possible. Why quickly? Well when I say quickly I'm really saying I'm committed, and...
Bjarne's book is fantastic, especially for C++ syntax, but the one book that will really make you a competent C++ programmer is Meyers' Effective C++. Get it. Read it. I as well do not have a CS degree, but I work for a silicon valley startup. It is possible, you just have to be aware of what's out there and never stop...
555,038
555,651
Boost exception at runtime
Using this code: #include <fstream> #include <boost/archive/text_oarchive.hpp> using namespace std; int main() { std::ofstream ofs("c:\test"); boost::archive::text_oarchive oa(ofs); } I'm getting an unhandled exception at runtime on executing the boost archive line: boost::exception_detail::clone_impl<bo...
The following line is in error: std::ofstream ofs("c:\test"); The compiler would've spit out a warning (at least) if your file was called jest; but '\t' -- being the escape for inserting a tab, your error goes by uncaught. In short, the file will not be created. You can test this with: if (ofs.good()) { ... } Now, s...
555,108
555,113
Using "this" as a parameter to copy constructor
I have a c++ class, let's say it's called c, and I want to use the implicit copy constructor in one of the methods, like this: c c::do_something() { c copy = this; //I want implicit copy constructor here! copy.something_else(); //........// return copy; } However, gcc returns this error: error: invalid conve...
this is a pointer to an object so it should be c copy = *this;
555,223
555,313
using string iterators over char* in boost regex
I am trying to search a char* to find matches and store each match as a struct using boost regex. I do not know how to use the std::string iterators over char*. So I created std::string from char* and using them. But now I want pointers in the original char* which can only be found using std::string I created. See the ...
You can get the original pointer by sStrInput+what.position(0) I'm not sure, however, why do you need all the tricks with std::string. According to the documentation, boost::regex_search can search any range specified by bidirectional iterators (ie. char* is a bidirectional iterator, so you pass (str, str+strlen(str))...
555,292
555,305
Thread communication theory
What is the common theory behind thread communication? I have some primitive idea about how it should work but something doesn't settle well with me. Is there a way of doing it with interrupts?
Really, it's just the same as any concurrency problem: you've got multiple threads of control, and it's indeterminate which statements on which threads get executed when. That means there are a large number of POTENTIAL execution paths through the program, and your program must be correct under all of them. In general...
555,327
555,357
Check for valid image
I'm writing a program that downloads information from the web and part of that is images. At the moment I'm having a problem as the code to download the images is a different part to the code that displays them (under mvc). If a 404 is issued or the image download fails some way the display code pops a message propmt ...
Do you want to check whether the download would be successful? Or do you want to check that what is downloaded is, in fact, an image? In the former case, the only way to check is to try to access it and see what kind of HTTP response code you get. You can send an HTTP HEAD request to get the response code without actua...
555,505
555,524
When were the 'and' and 'or' alternative tokens introduced in C++?
I've just read this nice piece from Reddit. They mention and and or being "Alternative Tokens" to && and || I was really unaware of these until now. Of course, everybody knows about the di-graphs and tri-graphs, but and and or? Since when? Is this a recent addition to the standard? I've just checked it with Visual C++ ...
MSVC supports them as keywords only if you use the /Za option to disable extensions; this is true from at least VC7.1 (VS2003). You can get them supported as macros by including iso646.h. My guess is they believe that making them keywords by default would break too much existing code (and I wouldn't be surprised if the...
555,612
555,665
Constructor doesn't work for class inherited from std::string
when doing #include <string> class MyString : public std::string { public: MyString() {} }; But the usage below: MyString s = "Happy day"; MyString s("Happy Day"); MyString s = (MyString)"Happy day"; neither of them works. It seems that there's something to do with constructors/operators declaration/overrid...
You need to define some constructors for the different types that you want to be able to convert into your strings. These constructors can basically just hand the parameters through to the underlying std::string. If you don't manually create them, the compiler creates a default- and a copy-constructor for you: MyString...
555,681
555,688
nested classes and references to outside classes (c++)
This is quite straightforward - gcc fails to to compile this sample code (c++). class myclass { struct mystruct { myclass something; int something_else; }; }; It tells me, that Field 'something' has incomplete type. I probably miss something trivial, because I'm quite new in c++, but why can'...
You can't put an object into itself. Perhaps you wanted a pointer to myclass.