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
640,874
644,136
How do draw to a texture in OpenGL
Now that my OpenGL application is getting larger and more complex, I am noticing that it's also getting a little slow on very low-end systems such as Netbooks. In Java, I am able to get around this by drawing to a BufferedImage then drawing that to the screen and updating the cached render every one in a while. How would I go about doing this in OpenGL with C++? I found a few guides but they seem to only work on newer hardware/specific Nvidia cards. Since the cached rendering operations will only be updated every once in a while, i can sacrifice speed for compatability. glBegin(GL_QUADS); setColor(DARK_BLUE); glVertex2f(0, 0); //TL glVertex2f(appWidth, 0); //TR setColor(LIGHT_BLUE); glVertex2f(appWidth, appHeight); //BR glVertex2f(0, appHeight); //BR glEnd(); This is something that I am especially concerned about. A gradient that takes up the entire screen is being re-drawn many times per second. How can I cache it to a texture then just draw that texture to increase performance? Also, a trick I use in Java is to render it to a 1 X height texture then scale that to width x height to increase the performance and lower memory usage. Is there such a trick with openGL?
Hey there, thought I'd give you some insight in to this. There's essentially two ways to do it. Frame Buffer Objects (FBOs) for more modern hardware, and the back buffer for a fall back. The article from one of the previous posters is a good article to follow on it, and there's plent of tutorials on google for FBOs. In my 2d Engine (Phoenix), we decided we would go with just the back buffer method. Our class was fairly simple and you can view the header and source here: http://code.google.com/p/phoenixgl/source/browse/branches/0.3/libPhoenixGL/PhRenderTexture.h http://code.google.com/p/phoenixgl/source/browse/branches/0.3/libPhoenixGL/PhRenderTexture.cpp Hope that helps!
640,983
641,008
Detect newline byte from filestream
I'm trying to collect information from a textfile which contains names of organisations (without spaces) and floating integers. I want to store this information in an array structure. The problem I'm having so far is collecting the information. Here is a sample of the textfile: CBA 12.3 4.5 7.5 2.9 4.1 TLS 3.9 1 8.6 12.8 4.9 I can have up to 128 different numbers for each organisation, and up to 200 organisations in the textfile. This is what my structure looks like so far: struct callCentre { char name[256]; float data[20]; }; My main: int main() { callCentre aCentre[10]; getdata(aCentre); calcdata(aCentre); printdata(aCentre); return 0; } And the getdata function: void getdata(callCentre aCentre[]) { ifstream ins; char dataset[20]; cout << "Enter the name of the data file: "; cin >> dataset; ins.open(dataset); if(ins.good()) { while(ins.good()) { ins >> aCentre[c].name; for(int i = 0; i < MAX; i++) { ins >> aCentre[c].data[i]; if(ins == '\n') break; } c++; } } else { cout << "Data files couldnt be found." << endl; } ins.close(); } What I'm trying to achieve in my getdata function is this: store the organisation name first into the structure, then read each float into the data array until the program detects a newline byte. However, so far my check for the newline byte isn't working. Assume that variables c and MAX are already defined. How should I go about this properly?
char byte = ins.peek(); Or if(ins.peek() == '\n') break; (Edit): You'll want to also check for an eof after your peek(), because some files may not have a ending newline. I'd like to point out that you might want to consider using a vector<callCentre> instead of a static array. If your input file length exceeds the capacity of the array, you'll walk all over the stack.
641,043
641,056
Pointer problems with overloading in C++?
Pointers present some special problems for overload resolution. Say for example, void f(int* x) { ... } void f(char* x) { ...} int main() { f(0); } What is wrong with calling f(0)? How can I fix the function call for f(0)?
f((int*) 0) or f((char *) 0) But if you find yourself doing this I would take another look at your design.
641,050
1,698,298
What tools exist for comparing C++ code to coding guidelines?
There exist tools for comparing code against a custom specified set of coding guidelines/standards for a variety of languages (rather than pure static analysis for common defects). Examples include FxCop for .Net code and CheckStyle for Java, but I was wondering what examples people know of in the C++ world. An existing question was asked regarding free tools which provided examples like Vera but I was also wondering about commercial tools that may be available.
The full list that I managed to generate: PRQA's QA C++ Parasoft's C++Test MS Visual Studio Team System seems to have some functionality but it's hard to tell via their website. GrammaTech CodeSonar Coverity Extend The last two provide some functionality but not particularly customisable ones: Klocwork Insight Rational PurifyPlus
641,064
641,972
what is a domain error
in c++, <stdexcept> has a base class for 'domain errors', std::domain_error. i don't understand under what circumstances i should throw a domain error in my code. all of the other exception base classes are pretty self explanatory. i'm pretty sure that std::domain_error has nothing to do with internet domain names, per se, so please explain what class of error a domain error is and provide some examples.
Domain and range errors are both used when dealing with mathematical functions. On the one hand, the domain of a function is the set of values that can be accepted by the function. For example, the domain of the root square function is the set of positive real numbers. Therefore, a domain_error exception is to be thrown when the arguments of a function are not contained in its domain On the other hand, the range of a function is the set of values that the function can return. For example, the range of a function like this one: f(x) = -x² is the set of negative real numbers. So what is the point of the range_error? If the arguments of the function are in its domain, then the result must be in its range, so we shouldn't have any errors wrt the range...However, sometimes the value can be defined, but without being representable. For example, in C, the functions in <math.h> generate errors if the return value is too large (or too small) in magnitude to represent
641,089
641,127
Correct value for hWnd parameter of BeginPaint?
I am trying to make a Visual C++ 2008 program that plots some data in a Window. I have read from various places the correct way to do this is to override WndProc. So I made a Windows Forms Application in Visual C++ 2008 Express Edition, and I added this code to Form1.h, but it won't compile: public: [System::Security::Permissions::PermissionSet(System::Security::Permissions::SecurityAction::Demand, Name="FullTrust")] virtual void WndProc(Message %m) override { switch(m.Msg) { case WM_PAINT: { HDC hDC; PAINTSTRUCT ps; hDC = BeginPaint(m.HWnd, &ps); // i'd like to insert GDI code here EndPaint(m.Wnd, &ps); return; } } Form::WndProc(m); } When I try to compile this in Visual C++ 2008 Express Edition, this error occurs: error C2664: 'BeginPaint' : cannot convert parameter 1 from 'System::IntPtr' to 'HWND' When I try using this->Handle instead of m.HWnd the same error occurs. When I try casting m.HWnd to (HWND), this error occurs: error C2440: 'type cast' : cannot convert from 'System::IntPtr' to 'HWND' Maybe I need to cast the m.HWnd to a pin_ptr or something.
If you were making a raw Win32 application then you could use those functions. If, on the other hand, you are making a WinForms application then you need to override the OnPaint event. Switch to the design view (The view that shows your form.) Click on the title bar of your form In the properties window (by default probably on your lower right screen) select the lightning bolt near the top. This will display a list of events. Scroll down to the paint event and double click it. You will end up with a Paint routine shell from which you can use the drawing functions of the graphics object. private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { e->Graphics->DrawRectangle(...) } If you really want to write raw Win32 code, let me know, and I can help you write a shell. In the time being if you are interested in Win32 I recommend Charles Petzold's Programming Windows 5th edition. If you want to learn C++ WinForms... well, I recommend switching to C# or VB.NET simply because they might be more intuitive. Hope this helps. Cheers.
641,335
656,650
How to figure out where to load program data from?
I've got a project written in C++ (with glibmm helping), and I'm using autotools to manage it. The question I have to ask is "HOW ON EARTH DO I FIGURE OUT WHERE TO LOAD STUFF FROM?". While I can find all the guides I want to on autotools, none answer this question. For example, maps go in $DATADIR/maps (usually /usr/[local/]share/myprogram/maps. Autotools does the right thing and puts them there, but how do I know whether it put them there or $HOME/myprogram/maps and load them appropriately (idealy it'd would search $PWD first, but that's easy).
Jonathan Leffler answer was helpful (he provided enough info for me to apt-get source evolution and find what I needed to do), but it didn't entirely answer my question, so I'll post the complete solution here: In configure.ac (or configure.in, whatever) I added the following lines at the end: # Defines so we know where to look privdatadir='${datadir}'/myprogram AC_SUBST(privdatadir) mapsdir='${privdatadir}'/maps AC_SUBST(mapsdir) In src/Makefile.am, the following was added: AM_CXXFLAGS = -DMYPROGRAM_MAPSDIR=\"$(mapsdir)\" In the actual C++ code, the following was used: const std::string file_directory (MYPROGRAM_MAPSDIR); // Defined in Makefile.am Once again, thanks Jonathan for showing me where to look, but I wanted to post the complete answer for posterity.
641,397
641,422
C++ best way to define cross-file constants
I am working on a game and have an interesting question. I have some game-wide constant values that I want to implement in one file. Right now I have something like this: constants.cpp extern const int BEGINNING_HEALTH = 10; extern const int BEGINNING_MANA = 5; constants.hpp extern const int BEGINNING_HEALTH; extern const int BEGINNING_MANA; And then files just #include "constants.hpp" This was working great, until I needed to use one of the constants as a template parameter, because externally-linked constants are not valid template parameters. So my question is, what is the best way to implement these constants? I am afraid that simply putting the constants in a header file will cause them to be defined in each translation unit. And I don't want to use macros. Thanks
Get rid of the extern and you're set. This code works perfectly fine in a header, because everything is "truly constant" and therefore has internal linkage: const int BEGINNING_HEALTH = 10; const int BEGINNING_MANA = 5; const char BEGINNING_NAME[] = "Fred"; const char *const BEGINNING_NAME2 = "Barney"; This code cannot safely be put in a header file because each line has external linkage (either explicitly or because of not being truly constant): extern const int BEGINNING_HEALTH = 10; extern const int BEGINNING_MANA = 5; const char *BEGINNING_NAME = "Wilma"; // the characters are const, but the pointer isn't
641,514
641,552
Are threading issues for C/C++ "system level programmers" significantly different from those faced by Java programmers?
I'm looking for a development job and see that many listings specify that the developers must be versed in multithreading. This appears both for Java job listings, and for C++ listings that involve "system programming" on UNIX. In the past few years I have been working with Java and using its various synchronization mechanisms. In the late 90s I did a lot of C++ work, though very little threads. In college, however, we used threads on Solaris. My question is whether there are significant differences in the issues that developers in C/C++ face compared to developers in Java, and whether any of the techniques to address them are fundamentally different. Java obviously includes some nicer mechanisms and synchronized versions of collections, etc. If I want to refresh or relearn threading on UNIX, what's the best approach? Which library should I look at? etc. Is there some great current tutorial on threads in c++?
The fundamental challenges of threading (e.g. synchronization, race conditions, inter-thread communication, resource cleanup), but Java makes thread much more manageable with garbage collection, exceptions, advanced synchronization objects, advanced debugging support with reflection. With C++, you are much more likely to have memory corruption and "impossible" race conditions. And you will need to write a lot more low-level thread primitives or rely on libraries (like boost) that are not part of the standardized language.
641,542
643,787
Why doesn't glCopyTexSubImage2D copy my square correctly?
here is the output: http://i43.tinypic.com/9a5zyx.png if things were working the way i wanted, the colors in the left square would match the colors in the right square. thanks for any help regarding the subject #include <gl/glfw.h> const char* title="test"; GLuint img; unsigned int w=64,h=64; int screenwidth,screenheight; void enable2d() { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glViewport(0,0,screenwidth,screenheight); glOrtho(0,screenwidth,screenheight,0,-1,1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glPushAttrib(GL_DEPTH_BUFFER_BIT|GL_LIGHTING_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glClearColor(0.0f, 0.0f, 0.0f, 0.5f); } void drawmytex() { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,img); glBegin(GL_QUADS); glTexCoord2i(0,0); glVertex2i(0,0); glTexCoord2i(1,0); glVertex2i(w,0); glTexCoord2i(1,1); glVertex2i(w,h); glTexCoord2i(0,1); glVertex2i(0,h); glEnd(); glDisable(GL_TEXTURE_2D); } void drawquad(int x,int y) { glBegin(GL_QUADS); glColor3f(0.0f,1.0f,0.0f); glVertex2i(x,y); glColor3f(1.0f,0.0f,1.0f); glVertex2i(x+w,y); glColor3f(0.0f,1.0f,1.0f); glVertex2i(x+w,y+h); glColor3f(0.0f,0.0f,1.0f); glVertex2i(x,y+h); glEnd(); } void texcopy() { if (!glIsTexture(img)) glDeleteTextures(1,&img); glGenTextures(1,&img); glBindTexture(GL_TEXTURE_2D,img); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,w,h,0,GL_RGBA,GL_UNSIGNED_BYTE,0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,w,h,0,-1,1); glViewport(0,0,w,h); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); drawquad(0,0); glBindTexture(GL_TEXTURE_2D,img); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //glCopyTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,0,0,w,h,0); glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,screenwidth,screenheight,0,-1,1); glViewport(0,0,screenwidth,screenheight); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main() { int running; glfwInit(); running=glfwOpenWindow(640,480,0,0,0,0,0,0,GLFW_WINDOW); if (!running) { glfwTerminate(); return 0; } glfwSetWindowTitle(title); glfwEnable(GLFW_STICKY_KEYS); glfwGetWindowSize(&screenwidth,&screenheight); enable2d(); texcopy(); do { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glLoadIdentity(); drawquad(64,0); drawmytex(); glfwSwapBuffers(); running=!glfwGetKey(GLFW_KEY_ESC)&&glfwGetWindowParam(GLFW_OPENED); GLenum error=glGetError(); if (error!=GL_NO_ERROR)running=error; glfwSleep(.017); } while (running==1); glDeleteTextures(1,&img); glfwTerminate(); return running; }
Try adding 'glColor3f(1,1,1);' in your 'drawmytex' function. I suspect that your texture is modulated (multiplied) with the current color, if so, the problem is not the texture copy but the way you display it.
641,724
641,854
Remove the common entities from two vector?
say I have vector<class1a>,vector<class1b> how to remove the common entities from both of them I have defined ==operator for the class1 objects class1a,class1b
The stl algorithms provide several functions to perform set operations, notably calculating the set symmetric difference, which is what you need. Here's an example of use: #include <algorithm> #include <vector> int main(int argc, char **argv) { std::vector<int> v1; v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); v1.push_back(6); std::vector<int> v2; v2.push_back(2); v2.push_back(4); v2.push_back(6); v2.push_back(8); // Ranges must be sorted! std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); std::vector<int> res; // Will contain the symmetric difference std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(res)); // Copy result to the output std::copy(res.begin(), res.end(), std::ostream_iterator<int>(cout, " ")); // Prints "1 3 5" return 0; } std::set_symmetric_difference takes two range (i.e. two pairs of OutputIterators) and an InputIterator where it will put the result. It also returns an iterator to the end of the result range. EDIT I just read your comments on your question. If you want the two original vectors to be modified, you can use std::set_difference: vector<int>::iterator endRange; endRange = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v1.begin()); v1.erase(endRange, v1.end()); Here, we put the result of the set difference v1 - v2 into v1. However, we can't do the vice-versa since v1 is now modified. The solution is to calculate the intersection of v1 and v2, and then the difference with this intersection std::set_intersection : vector<int> inter; set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(inter)); // inter is "2 4 6" v1.erase(set_difference(v1.begin(), v1.end(), inter.begin(), inter.end(), v1.begin()), v1.end()); // v1 is "1 3 5" v2.erase(set_difference(v2.begin(), v2.end(), inter.begin(), inter.end(), v2.begin()), v2.end()); // v2 is "8" I guess there are much more performant solutions, but this one is clear, and really convey your intents by using widely known stl algorithms.
641,826
641,904
What is __unwind$ in a linker map file
For VS2008 (C++) generated linker map files, what does the symbol "__unwind$" mean? I have a good chunk of them in the linker map file for my app. I have a log which says a crash happens at a particular offset say 'x'. When I look at the linker map for this offset, I find this __unwind$41357 corresponding to the offset. Also generally is there any reference to understand the file format of linker map files?
"Unwinding" is happens with a stack when an exception is thrown. The __ prefix indicates a compiler-generated symbol. So, based on the description, you get a crash between a throw and a catch. My assumption is that the destructors called are called from the __unwind$ functions. An inlined destructor wouldn't have its own stackframe, so it would show up in the calling __unwind$ function.
641,864
641,881
Returning a pointer to a vector element in c++
I have a vector of myObjects in global scope. I have a method which uses a std::vector<myObject>::const_iterator to traverse the vector, and doing some comparisons to find a specific element. Once I have found the required element, I want to be able to return a pointer to it (the vector exists in global scope). If I return &iterator, am I returning the address of the iterator or the address of what the iterator is pointing to? Do I need to cast the const_iterator back to a myObject, then return the address of that?
Return the address of the thing pointed to by the iterator: &(*iterator) Edit: To clear up some confusion: vector <int> vec; // a global vector of ints void f() { vec.push_back( 1 ); // add to the global vector vector <int>::iterator it = vec.begin(); * it = 2; // change what was 1 to 2 int * p = &(*it); // get pointer to first element * p = 3; // change what was 2 to 3 } No need for vectors of pointers or dynamic allocation.
641,935
733,928
WASAPI prevents Windows automatic suspend?
First time poster, be gentle ;-) I'm writing an audio app (in C++) which runs as a Windows service, uses WASAPI to take samples from the line in jack, and does some processing on it. Something I've noticed is that when my app is "recording", Windows won't automatically suspend or hibernate. I've registered for power event notifications and, if I push the suspend button myself, my service gets the appropriate power events and handles them ok. If I leave the system to suspend on its own, the power events are never received. If I remove the bits of code where I reference WASAPI, the power events are received as normal on both manual and automatic suspend. So it seems like there's something about using WASAPI that tells Windows to ignore the automatic suspend timer. Can anyone help explain this behavior, and is there anything I can do to stop it? I don't want my app to be one of those which misbehaves and prevents systems from suspending..
Many thanks to Larry for confirming this behaviour is by design and not me doing something silly. To work around this issue I used the Win32 CallNtPowerInformation() API to retrieve the system idle timer: SYSTEM_POWER_INFORMATION spi = {0}; NTSTATUS status = CallNtPowerInformation(SystemPowerInformation, NULL, 0, &spi, sizeof(spi)); if (NT_SUCCESS(status) && (spi.TimeRemaining==0)) { // should have gone to sleep } The spi.TimeRemaining member counts down (in seconds) from the time specified by the user in Control Panel e.g. "System standby after 1 hour", and gets reset whenever CPU usage (as a percentage) rises above spi.MaxIdlenessAllowed. If spi.TimeRemaining ever reaches zero, the system should have gone to sleep, so I close all my WASAPI handles and let it do so.
642,066
642,580
g++ undefined reference to constructor
I'm compiling and linking a cpp file against a pre-compiled library, and I'm getting an "undefined reference" error. Firstly, this is the command (the library in question is quicknet3, the program I'm compiling is trapper): g++ -w -g -I. -g -O3 -pipe -Wall -I/home/install/x86_64/include/quicknet3 -L/home/install/x86_64/lib -lquicknet3 -lintvec -lfltvec -o trapper trapper.cpp CMyException.cpp Here's the undefined reference error: /tmp/ccFuVczF.o: In function 'main': trapper.cpp:1731: undefined reference to 'QN_InFtrLabStream_PFile::QN_InFtrLabStream_PFile(int, char const*, _IO_FILE*, int)' The call in trapper.cpp (line 1731) is: IN_PFILE = new QN_InFtrLabStream_PFile(0, "", fp, 1); where fp is a FILE *, assigned as the result of an fopen call beforehand. The constructor being called is defined in the relevant header file (QN_Pfile.h), as follows: class QN_InFtrLabStream_PFile : public QN_InFtrLabStream { public: QN_InFtrLabStream_PFile(int a_debug, const char* a_dbgname, FILE* a_file, int a_indexed); (... other declarations ...) } The definition of the constructor is indeed given in QN_Pfile.cc: QN_InFtrLabStream_PFile::QN_InFtrLabStream_PFile(int a_debug,const char* a_dbgname, FILE* a_file, int a_indexed) : log(a_debug, "QN_InFtrLabStream_PFile", a_dbgname),file(a_file),indexed(a_indexed),buffer(NULL),sentind(NULL) { (... the usual constructor stuff :P ...) } I compiled the quicknet3 library myself, without error, and installed it to /home/install/x86_64/lib/libquicknet3.a So, I can't understand why the call from trapper.cpp is unable to find the reference to this constructor definition. The g++ arguments of -L/home/install/x86_64/lib -lquicknet3 should do the trick, right? Any ideas? Thanks, Roy
A quick workaround is to add /home/install/x86_64/lib/libquicknet3.a to g++ commandline. I you want to investigate further, if g++ is picking another copy of libquicknet3, you can pass -v to g++ so it will output its searching paths.
642,082
657,317
How to embed Windows Form in unmanaged ATL GUI?
I have a Windows form user control that is made COM visible. Now I want to embed that control into an ATL dialog GUI. The ATL project (unmanaged C++) shall only get the progID of the winform and dynamically create and embed it at runtime. Is this possible and if so, how do I do it?
I figured out a way to get it to work. The following code is using a CWnd called m_Control that is made to host a winform via a little documented version of CreateControl. Seems to work fine so far. If anyone sees any drawbacks, please comment or respond. AfxEnableControlContainer(); Microsoft::VisualC::MFC::CControlCreationInfoEx i; i.Init(System::Type::GetTypeFromProgID(gcnew System::String(sProgID)), CControlCreationInfo::ReflectionType); i.m_clsid = CLSID_WinFormsControl; POINT pt; pt.x = pt.y = 0; SIZE sz; sz.cx = sz.cy = 100; m_Control.CreateControl(i, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, &pt, &sz, CWnd::FromHandle(m_hWnd), ID_CONTROL);
642,213
642,258
How to implement a natural sort algorithm in c++?
I'm sorting strings that are comprised of text and numbers. I want the sort to sort the number parts as numbers, not alphanumeric. For example I want: abc1def, ..., abc9def, abc10def instead of: abc10def, abc1def, ..., abc9def Does anyone know an algorithm for this (in particular in c++) Thanks
I asked this exact question (although in Java) and got pointed to http://www.davekoelle.com/alphanum.html which has an algorithm and implementations of it in many languages.
642,229
642,447
Why do I need to use typedef typename in g++ but not VS?
It had been a while since GCC caught me with this one, but it just happened today. But I've never understood why GCC requires typedef typename within templates, while VS and I guess ICC don't. Is the typedef typename thing a "bug" or an overstrict standard, or something that is left up to the compiler writers? For those who don't know what I mean here is a sample: template<typename KEY, typename VALUE> bool find(const std::map<KEY,VALUE>& container, const KEY& key) { std::map<KEY,VALUE>::const_iterator iter = container.find(key); return iter!=container.end(); } The above code compiles in VS (and probably in ICC), but fails in GCC because it wants it like this: template<typename KEY, typename VALUE> bool find(const std::map<KEY,VALUE>& container, const KEY& key) { typedef typename std::map<KEY,VALUE>::const_iterator iterator; //typedef typename iterator iter = container.find(key); return iter!=container.end(); } Note: This is not an actual function I'm using, but just something silly that demonstrates the problem.
The typename is required by the standard. Template compilation requires a two step verification. During the first pass the compiler must verify the template syntax without actually supplying the type substitutions. In this step, std::map::iterator is assumed to be a value. If it does denote a type, the typename keyword is required. Why is this necessary? Before substituing the actual KEY and VALUE types, the compiler cannot guarantee that the template is not specialized and that the specialization is not redefining the iterator keyword as something else. You can check it with this code: class X {}; template <typename T> struct Test { typedef T value; }; template <> struct Test<X> { static int value; }; int Test<X>::value = 0; template <typename T> void f( T const & ) { Test<T>::value; // during first pass, Test<T>::value is interpreted as a value } int main() { f( 5 ); // compilation error X x; f( x ); // compiles fine f: Test<T>::value is an integer } The last call fails with an error indicating that during the first template compilation step of f() Test::value was interpreted as a value but instantiation of the Test<> template with the type X yields a type.
642,348
642,378
Does GetSystemInfo give you the total number of virtual CPUs (i.e. hyper-threaded)?
GetSystemInfo will give you the number of physical CPUs / cores, but I would like to know the total number of virtual CPUs. I.e. on the new Nahelam chips, they have 4 cores, but appear as 8 cpus. If GetSystemInfo doesn't give this information, what API do I need (I've seen a function for getting number of logical processors, but it is Vista only. I need to support XP)?
GetLogicalProcessorInformation Function ( Windows Vista, Windows XP Professional x64 Edition, Windows XP with SP3)
642,539
642,552
How does one avoid accidentally redeclaring global constants in C++?
I have a template matrix class class defined in a header called "Matrix.h". Certain matrices are used repeatedly in my program. I thought that I would define these in the "Matrix.h" header file, like so: const Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4, values); When I do this g++ complains that I redefined the constant in question. This happens because I include Matrix.h in two different source files. When the object files for these are compiled, both end up with a definition of the matrix above, causing the error message. My question is how do I avoid this situation? I want a constant that is accessible to more than one file, but I don't know where to put it.
If you don't want to split it between a header and implementation file, Declare your constant static (or declare it in anonymous namespace) to make definition private. Linker will not complain, but it will result in multiple private copies across compilation units. static Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4, values); Make an inline function that returns the constant. Inline function definitions produce "weak" symbols in object file, so linker will eliminate duplicates and pick one. inline const Matrix<GLfloat>& GET_B_SPLINE_TO_BEZIER_MATRIX() { const static Matrix<GLfloat> B_SPLINE_TO_BEZIER_MATRIX(4, 4, values); return B_SPLINE_TO_BEZIER_MATRIX; }
642,618
642,665
Compile error using cl.exe (Visual Studio 2008) for this cpp code
I'm getting compile error in this code #include<iostream> #include<cstdio> #include<string> using namespace std; void main(int argc,char *argv[]) { int i; for(i = 0;i<10;i++) fprintf(cout,"%d\n",i); fprintf(cout,"abc:\n"); string s; cin>>s; if(s == "resume") { for(i = 0;i<10;i++) fprintf(cout,"%d\n",i); } } Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. try.cpp C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C 4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc try.cpp(9) : error C2664: 'fprintf' : cannot convert parameter 1 from 'std::ostr eam' to 'FILE *' No user-defined-conversion operator available that can perform this conv ersion, or the operator cannot be called try.cpp(10) : error C2664: 'fprintf' : cannot convert parameter 1 from 'std::ost ream' to 'FILE *' No user-defined-conversion operator available that can perform this conv ersion, or the operator cannot be called try.cpp(16) : error C2664: 'fprintf' : cannot convert parameter 1 from 'std::ost ream' to 'FILE *' No user-defined-conversion operator available that can perform this conv ersion, or the operator cannot be called what is wrong?
std::fprintf(stdout, )
643,023
643,063
protected inheritance vs. public inheritance and OO design
When do you use each inheritance? class Base{}; class Derived: protected Base{}; class Derived2: public Base{}; My case: I have class called Snapshot which only contains GetXXX methods. It is a light-weight classed used to store current state of the Value class. I also use it for recovery, keeping instances of this class long after Value class instance are gone. A Manager class, processes instances of the Snapshot class. Let me show you the code: class Snapshot { public: Snapshot (const Snapshot * snap) { _x=snap->_x; _y=snap->_y; _z=snap->_z; } Snapshot (){_x=_y=_z=0;} int GetX(){return _x;} int GetY(){return _y;} int GetZ(){return _z;} ~virtual Snapshot(){} protected: int _x,_y,_z; }; class Value:public Snapshot { /*Very heavy class with a lot of components used to calculate _x, _y, _z*/ }; class Manager { public: void Process( const Snapshot * snap) { } }; How do you feel about this design? What are the alternatives? Thanks Solutions and issues Solution: I would create makeSnapshot function which would return Snapshot object by given Value object. Issues: major issue: I sent snapshots at very frequently (every second, even less), hence I don't want to incur the construction and destruction cost minor issue: semi-major issue I will have to make Value a friend of Snapshot, as I don't want to introduce setters.
Generally speaking I would use public inheritance, if I want to implement a specific interface, e.g. if my class is to be accessed thrugh a specific contract. Protected inheritance could be used, if you just want to reuse the functionality implemented in the parent. I would make Snapshot a pure virtual class, e.g. just an interface, and Value would implement the getXYZ methods. E.g. you probably don't need the _x,_y,_z members in Snapshot.
643,202
643,228
Send C++ string to C# string. Interop
I am new to inter process communication and need some help. I want to be able to send a string from a C++ program to a C# program. My problem is that the resultant string is gibberish. Here is my code: Sending program (C++): void transmitState(char* myStr) { HWND hWnd = ::FindWindow(NULL, _T("myApp v.1.0")); if (hWnd) { COPYDATASTRUCT cds; ::ZeroMemory(&cds, sizeof(COPYDATASTRUCT)); cds.dwData = 0; cds.lpData = (PVOID) myStr; cds.cbData = strlen(myStr) + 1; ::SendMessage(hWnd, WM_COPYDATA, NULL, (LPARAM)&cds); } } And the receiving program (C#) (I have already overridden the WndProc): private void OnCopyData(ref Message m) { COPYDATASTRUCT cds = new COPYDATASTRUCT(); cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); String myStr; unsafe { myStr = new String((char*) cds.lpData); } label1.Text = myStr; }
char* in C++ is ANSI character string (usually one byte per character), char* in C# is Unicode character string (like WCHAR* - two bytes per character). You in fact reinterpret_cast from char* to WCHAR*. This won't work. Use MultiByteToWideChar() on C++ side to convert.
643,317
643,337
Virtual behavior by storing pointers to member functions
Why is virtual behavior being prevented? class MyClass { //........ virtual double GetX(); virtual double GetSomethingElse(); virtual double GetT(); virtual double GetRR(); //........ }; class Processor { private: typedef double (MyClass::*MemFuncGetter)(); static map<std::string, MemFuncGetter> descrToFuncMap; public: static void Initialize(); void Process(Myclass m, string); }; void Processor::Initialize() { descrToFuncMap["X"]=&MyClass::GetX; descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse; descrToFuncMap["RR"]=&MyClass::GetRR; descrToFuncMap["T"]=&MyClass::GetT; }; void Processor::Process(MyClass *ms, const std::string& key) { map<std::string, Getter>::iterator found=descrToFuncMap.find(key); if(found!=descrToFuncMap.end()) { MemFuncGetter memFunc=found->second; double dResult=(ms).*memFunc(); std::cout<<"Command="<<key<<", and result="<<result<<std::end; } }
This line here: void Processor::Process(MyClass ms, const std::string& key) Try replacing it with void Processor::Process(MyClass &ms, const std::string& key) What is happening is called slicing, even though you may have passed in a sub-class of MyClass, when you call Process, a new MyClass object is made on the stack using MyCLass's copy-constructor. This new object is a MyClass in everyway, including having MyClass's virtual table. When you pass by reference, or with a pointer, no copy is made, and the reference to MyClass can be refering to an object that is really of a type SubClassOfMyClass. Edit: Well, the issue is with one of the many compile errors, if you get this all to compile it works just fine: class MyClass { public: //........ virtual double GetX() { return 0.0; } }; class MyClass2 : public MyClass { public: //........ virtual double GetX() { return 1.0; } }; class Processor { public: typedef double (MyClass::*MemFuncGetter)(); static void Initialize(); void Process(MyClass *m, const string &); private: static map<std::string, MemFuncGetter> descrToFuncMap; }; void Processor::Initialize() { descrToFuncMap["X"]=&MyClass::GetX; } void Processor::Process(MyClass *ms, const std::string& key) { map<std::string, MemFuncGetter>::iterator found=descrToFuncMap.find(key); if(found!=descrToFuncMap.end()) { MemFuncGetter memFunc=found->second; double dResult=(ms->*memFunc)(); std::cout<<"Command="<<key<<", and result="<<dResult<<std::endl; } } map<std::string, Processor::MemFuncGetter> Processor::descrToFuncMap; int main() { Processor::Initialize(); Processor p; MyClass2 mc2; p.Process(&mc2, "X"); } Which outputs: Command=X, and result=1
643,617
643,668
Passing a list of numbers to a function in C++ without building array first?
I'm trying to build a function that accepts an array in the following manner: int inCommon = findCommon({54,56,2,10}, 4); int findCommon(int nums[], int len){ for(int i=0; i<len; i++) cout<<nums[i]<<endl; return 1; } Note, that's not actually what my function does, but I do loop through the array. I'm just trying to determine if it's possible to pass an array like {54,56,2,10} instead of having to create an array and pass it? (like this: int theArray[]= {54,56,2,10}; int inCommon = findCommon(theArray,4);
This is not possible at the time. However, in the next C++ standard C++0x, this will be done using initalizer lists: int findCommon(std::initializer_list<int> nums) { std::initializer_list<int>::iterator it; for (it = nums.begin() ; it != nums.end() ; ++it) { std::cout << *it << std::endl; } return 1; } See this presentation from Bjarne Stroustrup, and this article from Wikipedia If you want to try C++0x features, you can check the last versions of gcc, that supports some of them.
643,738
643,779
What does `vcall'{0,{flat}}' signify in below example?
I am not sure if the question is already addressed. I was checking the one of the Stack overflow function and got this doubt. Lets check the code first: #include <string> #include <map> #include <iostream.h> class MyClass { public: virtual int Func() { return 0; } int Func2() { return 0; } }; class MyClass2 : public MyClass { public: int Func( ) { return 1; } int Func2() { return 1; } }; class Processor { private: typedef int (MyClass::*MemFuncGetter)(); static std::map<std::string, MemFuncGetter> descrToFuncMap; public: static void Initialize(); void Process(MyClass* m, const std::string&); }; std::map<std::string, Processor::MemFuncGetter> Processor::descrToFuncMap; void Processor::Initialize() { descrToFuncMap["Func"]=&MyClass::Func; descrToFuncMap["Func2"]=&MyClass::Func2; }; void Processor::Process(MyClass* ms, const std::string& key) { std::map<std::string, MemFuncGetter>::iterator found = descrToFuncMap.find(key); if(found != descrToFuncMap.end()) { MemFuncGetter memFunc = found->second; int dResult = (ms->*memFunc)(); cout << "Result is : "<< dResult <<endl; } } int main(int argc, char* argv[]) { Processor::Initialize(); Processor p; MyClass *pMC2 = new MyClass2; p.Process(pMC2, "Func"); p.Process(pMC2, "Func2"); delete pMC2; pMC2 = NULL; return 0; } In this example, the result is as expected: Result is : 1 Result is : 0 But when I debugged using VC 6 debugger and observed the value of memFunc in Processor::Process and found following values: In p.Process(pMC2, "Func"); call memFunc 0x004011bd [thunk]:`vcall'{0,{flat}}' In p.Process(pMC2, "Func2"); call memFunc 0x0040118b MyClass::Func2(void) I didn't understand thunk and flat in "[thunk]:`vcall'{0,{flat}}" ? Can anyone help me to understand the internals here ?
There is a pretty thorough explanation of what thunk means over on WikiPedia http://en.wikipedia.org/wiki/Thunk The gist of is thunk is the mechanism by which the C++ virtual table is accessed at runtime. It is setup to call the appropriate virtual function for the runtime type of the object. As to what the vcall{0,{flat}} means I am not 100% sure. My guess is that it's reporting the values by which the thunk is accessing the method. 0: Offset in the vtable {flat}: inheritance hierarchy is flat not multiple
644,397
644,427
c++ class with template cannot find its constructor
I have a problem I don't really understand. I have a class Node. template<class T> class node { protected: T _data; public: node(T data); }; This is in "node.h" file. In "node.cpp" file, there is this constructor: #include "node.h" template<class T> node<T>::node (T data) { _data = data; } While the compiler finds no error, the linker (ld) tells me: /usr/bin/ld: Undefined symbols: node<int>::node(int) the weird part... if I move the constructor from .cpp to .h file, everything works fine. Where is the problem?
The problem is that templates aren't classes - you don't normally write them in two separate files. Template classes are code that the compiler uses to generate classes. As such, your implementation code needs to effectively be inline, i.e., in the header as you discovered. For a fuller explanation of why it has to be this way, see the C++ FAQ Lite.
644,461
644,475
C++ - Constructor overloading - private and public
Can you tell me why the following code is giving me the following error - call of overloaded "C(int)" is ambiguous I would think that since C(char x) is private, only the C(float) ctor is visible from outside and that should be called by converting int to float. But that's not the case. class C { C(char x) { } public: C(float t) { } }; int main() { C p(0); }
This is discussed in "Effective C++" by Scott Meyer. The reason this is ambiguous is that they wanted to ensure that merely changing the visibility of a member wouldn't change the meaning of already-existing code elsewhere. Otherwise, suppose your C class was in a header somewhere. If you had a private C(int) member, the code you present would call C(float). If, for some reason, the C(int) member was made public, the old code would suddenly call that member, even though neither the old code, nor the function it called had changed. EDIT: More reasons: Even worse, suppose you had the following 2 functions: C A::foo() { return C(1.0); } C B::bar() { return C(1.0); } These two functions could call different functions depending on whether either foo or bar was declared as a friend of C, or whether A or B inherits from it. Having identical code call different functions is scary. (That's probably not as well put as Scott Meyer's discussion, but that's the idea.)
644,629
644,639
Base enum class inheritance
Is there a pattern where I can inherit enum from another enum in C++?? Something like that: enum eBase { one=1, two, three }; enum eDerived: public eBase { four=4, five, six };
Not possible. There is no inheritance with enums. You can instead use classes with named const ints. Example: class Colors { public: static const int RED = 1; static const int GREEN = 2; }; class RGB : public Colors { static const int BLUE = 10; }; class FourColors : public Colors { public: static const int ORANGE = 100; static const int PURPLE = 101; };
644,673
644,693
Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?
I am trying to efficiently make a copy of a vector. I see two possible approaches: std::vector<int> copyVecFast1(const std::vector<int>& original) { std::vector<int> newVec; newVec.reserve(original.size()); std::copy(original.begin(), original.end(), std::back_inserter(newVec)); return newVec; } std::vector<int> copyVecFast2(std::vector<int>& original) { std::vector<int> newVec; newVec.swap(original); return newVec; } Which of these is preferred, and why? I am looking for the most efficient solution that will avoid unnecessary copying.
Your second example does not work if you send the argument by reference. Did you mean void copyVecFast(vec<int> original) // no reference { vector<int> new_; new_.swap(original); } That would work, but an easier way is vector<int> new_(original);
644,889
645,083
What is the best Evaluation Kit for Learning Embedded C/C++ Development?
I am trying to improve my embedded C/C++ development on ARM architecture. I have recently moved from 68K development to ARM and wanted to use some of my spare time to dig into the platform and learn the best practices especially on developing for mobile platforms. Preferably 32bit architecture will be helpful with supporting development tools. A bit of fun during the learning process may enhance my understanding of the platform
ST Micro has a very attractively priced (and packaged too) kit for their ARM Cortex-M3 based STM32 line. MSRP runs about US$35 for the STM32-PRIMER with 128x128 color LCD, MEMS accelerometer, push button, LEDs, USB, and some spare GPIOs all in a package that includes a battery and USB to JTAG debug connection. A GCC toolchain and a commercial debugger are supposed to come with it as well. I have one on order, and will try to remember to edit this answer to include a quick review after it arrives next week sometime. They have a new model based on an STM32 with more FLASH and RAM on chip that also has a micro-SD card connector, and a larger LCD that includes a resistive touchscreen that runs just over $100 if you can find it in stock. Luminary Micro has a number of inexpensive demo/eval board kits as well. The people behind the eLua project (a complete Lua programming environment running in SoC and MCU scale devices) seem to like the Luminary Micro product line, but I have no personal experience with them.
645,046
645,058
C++ Pointers to Member Functions Inheritance
I have a need to be able to have a super class execute callbacks defined by a class that inherits from it. I am relatively new to C++ and from what I can tell it looks like the subject of member-function-pointers is a very murky area. I have seen answers to questions and random blog posts that discuss all sorts of things, but I am not sure if any of them are specifically dealing with my question here. Here is a simple chunk of code that illustrates what I am trying to do. The example might not make a lot of sense, but it accurately resembles the code I am trying to write. class A { protected: void doSomething(void (A::*someCallback)(int a)) { (*this.*someCallback)(1234); } }; class B : public A { public: void runDoIt() { doSomething(&B::doIt); } void runDoSomethingElse() { doSomething(&B::doSomethingElse); } protected: void doIt(int foo) { cout << "Do It! [" << foo << "]\n"; } void doSomethingElse(int foo) { cout << "Do Something Else! [" << foo << "]\n"; } }; int main(int argc, char *argv[]) { B b; b.runDoIt(); b.runDoSomethingElse(); }
If you can use boost libraries, I would suggest you use boost::function for the task at hand. class A { public: void doSomething( boost::function< void ( int ) > callback ) { callback( 5 ); } }; Then any inheriting (or external class) can use boost::bind do make a call: class B { public: void my_method( int a ); }; void test() { B b; A a; a.doSomething( boost::bind( &B::my_method, &b, _1 ) ); }; I have not checked the exact syntax and I have typed it from the top of my head, but that is at least close to the proper code.
645,062
645,095
Visual Studio projects with multiple folders
Is there an easy way to use multiple folders in a project with Visual Studio? It has "filters" which look like folders, but it would be really nice to be able to make folders and insert files in them inside VS. Is there an add-in or secret option to enable this behavior?
With VC++, the folders do not correspond directly with what's on your file system. They are simply used to help you organize your project in an independent manner. The reason they have this design decision is because with C++ you typically have many include and source directories. More on Filters: At the top of your "Solution Explorer" window you will see a toolbar button that when hovered over says "Show All Files". If this button is pressed it does not show you a Folder/Filter structure. If this button is not pressed it shows you the Folder/Filter structure. To add a new Folder/Filter, right click on a project of your solution and select Add -> New Filter. Note that for each Folder/Filter that you create you can go into the Folder/Filter properties and set things such as: Parse files: Whether to parse the files in this folder for auto completion SCC Files: Whether the files in this folder should be considered for source control Filter: Specifies the file types that this folder will hold by default.
645,165
645,171
#include directive: relative to where?
I have looked in The C++ Programming Language to try to find the answer to this. When I #include "my_dir/my_header.hpp" in a header, where does it look for this file? Is it relative to the header, relative to the source file that included it, or something else?
Implementation defined. See what is the difference between #include <filename> and #include “filename”.
645,168
645,273
How to write a std::bitset template that works on 32 and 64-bit
Consider the following code template<unsigned int N> void foo(std::bitset<N> bs) { /* whatever */ } int main() { bitset<8> bar; foo(bar); return 0; } g++ complains about this on 64 bit because the <8> gets interpreted as an unsigned long int, which doesn't exactly match the template. If I change the template to say unsigned long int, then 32-bit compiles complain. Obviously one way to fix this is to change bitset<8> to bitset<8ul>, but is there any way to re-write the template part so that it will work with whatever the default interpretation of a numeric literal is?
The problem isn't whether or not you write 8u or 8. The problem has to do with the type of the template parameter of your function template. Its type has to match the one used in the declaration of std::bitset. That's size_t according to the Standard (section 23.3.5) namespace std { template<size_t N> class bitset { public: // bit reference: ... The exception are array dimensions, for which you can use any integer type (even bool - then the only size that can be accepted is 1 of course): // better size_t (non-negative), but other types work too template<int N> void f(char(&)[N]); But in other occasions, types have to match. Note that this is only true for autodeduced template arguments, but not for explicitly given ones. The reason is that for deduced ones, the compiler tries to figure out the best match between actual template arguments and what it deduced from the call to it. Many otherwise implicit conversions are disallowed then. You have the full range of conversions available if you put the argument explicit (ignoring the solution of using size_t now to make my point) template<int N> void foo(std::bitset<N> bs) { /* whatever */ } int main() { bitset<8> bar; foo<8>(bar); // no deduction, but full range of conversions }
645,268
645,306
In COM: should I call AddRef after CoCreateInstance?
Does CoCreateInstance automatically calls AddRef on the interface I'm creating or should I call it manually afterwards?
The contract with COM is anytime you are handed an object from a function like this, such as CoCreateInstance(), QueryInterface() (which is what CoCreateInstance() ultimately calls), etc, the callee always calls AddRef() before returning, and the caller (you) always Release() when you are done. You can use CComPtr<> to make this simpler, and it just does the right thing. Now if you need to hand this pointer out to another object that expects it to be usable beyond the lifetime of your object, then you need to call AddRef() before giving it out. I recommend Essential COM by Don Box for further reading on this topic.
645,290
645,298
How to hook up LED lights in C++ without microcontroller?
I want to light up/off LEDs without a microcontroller. I'm looking to control the LEDs by writing a C++ program. but the problem im having is hooking them up is there a free way to do !!!! I'm using Windows XP if that is relevant. I have LEDs but I don't have a microcontroller. Well, I found some functions but their headers are not working, so can someone help me find headers? Here is an example of what I'm talking about: poke(0x0000,0x0417,16); gotoxy(1,1); printf("Num Lock LED is now on r"); delay(10); Also, does anyone have a "Kernel Programming" eBook? I also need a circuit diagram to show where to hook up the LEDs.
That completely depends on which hardware you have, which determines which driver you need. Back then, i got a simple led and put it into the printer LPT port. Then i could write a byte to address 0x0378h and the bits in it determined whether a pin had power or not (using linux). For windows, you need a driver that allows you to access the lpt port directly. I did it with a friend back then too, and it worked nicely (we built up a traffic light :)) Read this page (click on Parallel Port on the left. For some reason, i cannot link directly to it) for details on windows. And read man outb on linux. Now, that Port is really old. But if you have some machine around that still got one, i think it's a lot of fun to play with it. Anyway, i've got a fritz box that has a neat LED. One can connect to it via telnet and then write something (i forgot the numbers) into /proc/led iirc. A kernel driver then interprets the number and makes the right LED blink. That's another way of doing it :)
645,595
645,604
How would you remove elements of a std::vector based on some property of the elements?
If for instance you have a std::vector<MyClass>, where MyClass has a public method: bool isTiredOfLife(), how do you remove the elements that return true?
I prefer remove_if v.erase(remove_if(v.begin(), v.end(), mem_fun_ref(&MyClass::isTiredOfLife)), v.end()); remove_if returns an iterator pointing after the last element that's still in the sequence. erase erases everything from its first to its last argument (both iterators).
645,747
4,170,902
Sharing precompiled headers between projects in Visual Studio
I have a solution with many Visual C++ projects, all using PCH, but some have particular compiler switches turned on for project-specific needs. Most of these projects share the same set of headers in their respective stdafx.h (STL, boost, etc). I'm wondering if it's possible to share PCH between projects, so that instead of compiling every PCH per-project I could maybe have one common PCH that most projects in the solution could just use. It seems possible to specify the location of the PCH as a shared location in the project settings, so I have a hunch this could work. I'm also assuming that all source files in all projects that use a shared PCH would have to have the same compiler settings, or else the compiler would complain about inconsistencies between the PCH and the source file being compiled. Has anyone tried this? Does it work? A related question: should such a shard PCH be overly inclusive, or would that hurt overall build time? For example, a shared PCH could include many STL headers that are widely used, but some projecst might only need <string> and <vector>. Would the time saved by using a shared PCH have to be paid back at a later point in the build process when the optimizer would have to discard all the unused stuff dragged into the project by the PCH?
Yes it is possible and I can assure you, the time savings are significant. When you compile your PCH, you have to copy the .pdb and .idb files from the project that is creating the PCH file. In my case, I have a simple two file project that is creating a PCH file. The header will be your PCH header and the source will be told to create the PCH under project settings - this is similar to what you would do normally in any project. As you mentioned, you have to have the same compile settings for each configuration otherwise a discrepancy will arise and the compiler will complain. Copying the above mentioned files every time there is a rebuild or every time the PCH is recompiled is going to be a pain, so we will automate it. To automate copying, perform a pre-build event where the above mentioned files are copied over to the appropriate directory. For example, if you are compiling Debug and Release builds of your PCH, copy the files from Debug of your PCH project over to your dependent project's Debug. So a copy command would look like this copy PchPath\Debug*.pdb Debug\ /-Y Note the /-Y at the end. After the first build, each subsequent build is incrementally compiled, therefore if you replace the files again, Visual Studio will complain about corrupted symbols. If they do get corrupted, you can always perform a rebuild, which will copy the files again (this time it won't skip them as they no longer exist - the cleanup deletes the files). I hope this helps. It took me quite some time to be able to do this, but it was worth it. I have several projects that depend on one big framework, and the PCH needs to be compiled only once. All the dependent projects now compile very quickly. EDIT: Along with several other people, I have tested this under VS2010 and VS2012 and it does appear to work properly.
645,778
645,855
What are the advantages and disadvantages of separating declaration and definition as in C++?
In C++, declaration and definition of functions, variables and constants can be separated like so: function someFunc(); function someFunc() { //Implementation. } In fact, in the definition of classes, this is often the case. A class is usually declared with it's members in a .h file, and these are then defined in a corresponding .C file. What are the advantages & disadvantages of this approach?
Historically this was to help the compiler. You had to give it the list of names before it used them - whether this was the actual usage, or a forward declaration (C's default funcion prototype aside). Modern compilers for modern languages show that this is no longer a necessity, so C & C++'s (as well as Objective-C, and probably others) syntax here is histotical baggage. In fact one this is one of the big problems with C++ that even the addition of a proper module system will not solve. Disadvantages are: lots of heavily nested include files (I've traced include trees before, they are surprisingly huge) and redundancy between declaration and definition - all leading to longer coding times and longer compile times (ever compared the compile times between comparable C++ and C# projects? This is one of the reasons for the difference). Header files must be provided for users of any components you provide. Chances of ODR violations. Reliance on the pre-processor (many modern languages do not need a pre-processor step), which makes your code more fragile and harder for tools to parse. Advantages: no much. You could argue that you get a list of function names grouped together in one place for documentation purposes - but most IDEs have some sort of code folding ability these days, and projects of any size should be using doc generators (such as doxygen) anyway. With a cleaner, pre-processor-less, module based syntax it is easier for tools to follow your code and provide this and more, so I think this "advantage" is just about moot.
645,888
645,894
Process cannot be resumed after having been suspended
CreateProcess suspended but it can't be resumed. Here is my code: bool success=CreateProcess(m_Process, NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS||CREATE_SUSPENDED, NULL, NULL, &suInfo, &procInfo); if(!success){ MessageBoxA(0,"Could not create process...","ERROR",MB_OK); return 1; } //we created it //all good so go! ResumeThread(procInfo.hThread); Why this doesn't work?
Remove one of the "|". This ends up as a one since it's a logical expression in your case. The constant for this is DEBUG_PROCESS, so you're debugging the child process.
645,994
646,001
Why is 'this' a pointer and not a reference?
I was reading the answers to this question C++ pros and cons and got this doubt while reading the comments. programmers frequently find it confusing that "this" is a pointer but not a reference. another confusion is why "hello" is not of type std::string but evaluates to a char const* (pointer) (after array to pointer conversion) – Johannes Schaub - litb Dec 22 '08 at 1:56 That only shows that it doesn't use the same conventions as other (later) languages. – le dorfier Dec 22 '08 at 3:35 I'd call the "this" thing a pretty trivial issue though. And oops, thanks for catching a few errors in my examples of undefined behavior. :) Although I don't understand what info about size has to do with anything in the first one. A pointer is simply not allowed to point outside allocated memory – jalf Dec 22 '08 at 4:18 Is this a constant poiner? – yesraaj Dec 22 '08 at 6:35 this can be constant if the method is const int getFoo() const; <- in the scope of getFoo, "this" is constant, and is therefore readonly. This prevents bugs and provides some level of guarantee to the caller that the object won't change. – Doug T. Dec 22 '08 at 16:42 you can't reassign "this". i.e you cannot do "this = &other;", because this is an rvalue. but this is of type T*, not of type T const . i.e it's a non-constant pointer. if you are in a const method, then it's a pointer to const. T const . but the pointer itself is nonconst – Johannes Schaub - litb Dec 22 '08 at 17:53 think of "this" like this: #define this (this_ + 0) where the compiler creates "this_" as a pointer to the object and makes "this" a keyword. you can't assign "this" because (this_ + 0) is an rvalue. of course that's not how it is (there is no such macro), but it can help understand it – Johannes Schaub - litb Dec 22 '08 at 17:55 My question is, why is this a pointer a not a reference? Any particular reason for making it a pointer? Some further arguments why this being a reference would make sense: Consider Item 1 from More Effective C++ : use references when it is guaranteed that we have a valid object i.e. not a NULL (my interpretation). Furthermore, references are considered safer than pointers (because we can't screw the memory up with a stray pointer). Thirdly, the syntax for accessing references (.) is a little bit nicer and shorter than accessing pointers (-> or (*)).
When the language was first evolving, in early releases with real users, there were no references, only pointers. References were added when operator overloading was added, as it requires references to work consistently. One of the uses of this is for an object to get a pointer to itself. If it was a reference, we'd have to write &this. On the other hand, when we write an assignment operator we have to return *this, which would look simpler as return this. So if you had a blank slate, you could argue it either way. But C++ evolved gradually in response to feedback from a community of users (like most successful things). The value of backward compatibility totally overwhelms the minor advantages/disadvantages stemming from this being a reference or a pointer.
646,116
646,282
Open Source & Cross Platform Multiplayer/Networking Libraries?
While raknet seems fairly interesting and really appealing from a feature-point of view, its licensing terms seem to be possibly troublesome for GPL'ed projects that may be leveraged commercially, something which is explicitly forbidden by the terms of the creative commons license. While there's also opentnl, it doesn't seem to be as actively maintained anymore nowadays, in fact downloading the latest stable tarball even fails during compilation because it doesn't seem to support gcc >= 3.0 (?) Of course, there's still also enet, but this one cannot be really compared to the abstract features that are supported by raknet/opentnl. So, apart from any non-trivial dependencies such as ACE, Boost or Poco, are there any viable alternatives for embedding a fairly compact, well-maintained UDP-networking library? Thanks
The wiki of Ogre3D provides a list of networking libraries and a short description for them.
646,217
646,222
How to run a bash script from C++ program
Bash scripts are very useful and can save a lot of programming time. So how do you start a bash script in a C++ program? Also if you know how to make user become the super-user that would be nice also. Thanks!
Use the system function. system("myfile.sh"); // myfile.sh should be chmod +x
646,392
646,396
How do perform a generic print for key type and map
With reference to this question StackoVerflow 529831, this was one of the suggested approaches template<typename Map> typename Map::const_iterator greatest_less(Map const& m, typename Map::key_type const& k) { //How to print K and Map m typename Map::const_iterator it = m.lower_bound(k); if(it != m.begin()) { return --it; } return m.end(); } I would be interested in printing key K and Map m, How would go about this.
Use the << operator, making sure that << is defined for both your Map::key_type and Map::data_type types (you will know if that is not the case as the code will not compile.) cout << k << endl; for (typename Map::const_iterator it = m.begin(); it != m.end(); ++i) { cout << it->first << " -> " << it->second << endl; } e.g. if your Map::data_type is a struct fraction with members float numerator and float denominator, ostream& operator<<(ostream& os, const fraction& obj) { return os << obj.numerator << '/' << obj.denominator; }
646,423
646,502
Using a DLL with .h header in C++
I have been given a small library, consisting of a .dll, a .h header and a .def file. I'm fairly sure the library was written in C, but possibly C++. Is it possible for me to access the functions in the library without using the LoadLibrary/GetProcAddress/FreeLibrary method that is usually talked about. I have no .lib file - is it usual to have one? I've literally spent the past 2 days looking this up. It seems that since I've been given a header file defining the functions I wish to use from the dll, and a .def file I shouldn't need to explicitly 'load' each function manually (LoadLibrary/GetProAddress/FreeLibrary) - in my case I will be using around 5 or 6 functions from the .dll, but there are around 70 available and it seems that would be a ball-ache and result in an unnecessary mess of code. Thanks for any advice.
Visual C++ has "lib" - look it up in the online help. Use "lib /def" to make the .lib file.
646,427
646,429
Should destructors be threadsafe?
I was going through a legacy code and found the following snippet: MyClass::~MyClass() { EnterCriticalSection(&cs); //Access Data Members, **NO Global** members are being accessed here LeaveCriticalSection(&cs); } I am wondering will it help by any chance to guard the destructor ? Consider a scenario : 1. Thread1 - About to execute any of the member function which uses critical section 2. Thread2- About to execute destructor. If the order of execution is 1=>2 then it might work. But what if the order is reversed ? Is it a design issue ?
The destructor should not be called when the object is in use. If you're dealing with such a situation, it needs a fundamental fix. However, the destructor might want to alter some other thing (which is unrelated to the class being destructed) and it might need a critical section (e.g. like decrementing a global counter).
646,468
646,478
How to Rotate a 2D Array of Integers
I am programming a Tetris clone and in my game I store my tetromino blocks as 4x4 arrays of blocks. I now need to be able to rotate the integer positions in the arrays so that I get a rotated tetris block. I cannot simply rotate the texture because all my collision detection, etc has been designed to work with the 2D array. The game is written in C# using XNA. How can i possibly rotate my 2D array of ints by 90 degrees clockwise/counter clockwise. Here is how my 'L' block is stored as an example. 0 1 0 0 0 1 0 0 0 1 1 0 0 0 0 0 Thanks for your help.
If they're a 2D array, you can implement rotation by copying with different array access orders. i.e., for a clockwise rotation, try: int [,] newArray = new int[4,4]; for (int i=3;i>=0;--i) { for (int j=0;j<4;++j) { newArray[j,3-i] = array[i,j]; } } Counter-clockwise is similar.
646,559
646,563
Two files containing definition of main() Visual Studio?
I have created a project in Visual Studio 2008 Professional Edition. This project contains one .cpp file for each assignment like this... [-]Source Files \ |-- 233.cpp |-- test.cpp And each file contains definition of main(). Action:CTRL+F5 Error 1 error LNK2005: _main already defined in 233.obj test.obj Error 2 fatal error LNK1169: one or more multiply defined symbols found How do I compile and see output of each file ? Thanks.
You can't have 2 functions called main() in a single project. What you should do is change the names of the functions, and then call them from a new main() function which would function as a menu. If you make them separate projects, you can switch which one to run with Solution Properties -> Startup Project.
646,660
646,667
Strange temporary array corruption
I am attempting to create a permutation, and I receive this strange error when I finish my problem: Stack around the variable "temp" was corrupted the segment of the variable is within a nested for loop: for(int i = 0 ; i < str_length ; i++) { for(int j = 0 ; j < str_length ; j++) { char temp[1]; temp[1] = text[i]; text[i] = text[j]; text[j] = temp[1]; cout << text << endl; } } text is initialized outside of the for loop as a string, and I get the same error when i make temp[1] into a char or an int. The program works fine but I am concern why I am receive this error, does anyone know why?
You just need to use char temp; and acces it as temp = text[i];, etc. You're accessing a point on the stack one byte PAST temp, which is invalid. In this case, since you only want a single char, there's no need for an array at all.
646,673
646,682
How can I get FindFirstFile to sort files
I am using the standard FindFirst and FindNext to retrieve all files in a directory but I need the results to come back sorted ( in the same order that clicking on the name column in explorer would sort them basically ) How can I achive this This has to be done via Win32 Thanks
You can use the Indexing Service for this, but I would recommend just to handle the sorting yourself while using FindFirstFile. Sorting is not possible with the FindFirstFile Win32 API. There is a slightly more advanced FindFirstFileEx, but even that does not allow sorting. There is a Raymond Chen post on The Old New Thing about FindFirstFile's limitations. Your best bet is probably to load all results into a vector, and then sort that.
646,737
646,762
Map of boost function of different types?
i was wondering if there was a way to do this in C++? void func1(const std::string& s) { std::cout << s << std::endl; } void func2(int me) { std::cout << me << std::endl; } int main() { std::map<std::string, boost::function< ??? > > a_map; a_map["func1"] = &func1; a_map["func1"]("HELLO"); } Is there any way to do what i have above using boost function and a map?
There are ways to store the functions, the problem is, in order to be able to call the function with the desired argument you'd have to know the calling signature of the function anyways, and if you have that information, you might as well use separate maps, or use a more complicated object than boost::function. If you're willing to do a bit of work and have a finite number of signatures, you could just do something like this: class MultiFunc { protected: MultiFunc() {} public: typedef void (*stringFunc)(const std::string&); typedef void (*intFunc)(int); static MultiFunc *Create(stringFunc function); static MultiFunc *Create(intFunc function); virtual void operator()(const string &) { throw exception(); } virtual void operator()(int) { throw exception(); } virtual ~MultiFunc(); }; class MultiFuncString : public MultiFunc { private: stringFunc Function; public: MultiFuncString(stringFunc function) : Function(function) {} virtual void operator()(const string &arg) { Function(arg); } }; class MultiFuncInt : public MultiFunc { private: intFunc Function; public: MultiFuncInt(intFunc function) : Function(function) {} virtual void operator()(int arg) { Function(arg); } }; MultiFunc *MultiFunc::Create(MultiFunc::stringFunc function) { return new MultiFuncString(function); } MultiFunc *MultiFunc::Create(MultiFunc::intFunc function) { return new MultiFuncInt(function); } void func1(const std::string& s) { std::cout << s << std::endl; } void func2(int me) { std::cout << me << std::endl; } int main() { map<string, MultiFunc *> a_map; a_map["func1"] = MultiFunc::Create(&func1); (*a_map["func1"])("Hello"); a_map["func2"] = MultiFunc::Create(&func2); (*a_map["func2"])(3); // Remember to delete the MultiFunc object, or use smart pointers. } This outputs: Hello 3 Unfortunately, you can't make templated virtual functions or you easily generalize this all.
647,074
647,075
How to make Linux C++ GUI apps
What is the easiest way to make Linux C++ GUI apps? I'm using GNOME and ubuntu 8.10.
I personally prefer QT as I prefer working with the signal/slots mechanism and just find it easy to develop applications quickly with it. Some of your other options would be wxWidgets and GTK+.
647,092
647,108
Should a list of objects be stored on the heap or stack?
I have an object(A) which has a list composed of objects (B). The objects in the list(B) are pointers, but should the list itself be a pointer? I'm migrating from Java to C++ and still haven't gotten fully accustomed to the stack/heap. The list will not be passed outside of class A, only the elements in the list. Is it good practice to allocate the list itself on the heap just in case? Also, should the class that contains the list(A) also be on the heap itself? Like the list, it will not be passed around.
Bear in mind that The list would only be on the stack if Object-A was also on the stack Even if the list itself is not on the heap, it may allocate its storage from the heap. This is how std::list, std::vector and most C++ lists work – the reason is that stack-based elements cannot grow. These days most stacks are around 1mb, so you'd need a pretty big list of pretty big objects before you need to worry about it. Even if your stack was only about 32kb you could store close to eight thousand pointers before it would be an issue. IMO people new to the explicit memory management in C/C++ can have a tendency to overthink these things. Unless you're writing something that you know will have thousands of sizable objects just put the list on the stack. Unless you're using giant C-style arrays in a function the chances are the memory used by the list will end up in the heap anyway due to #1 and #2 above.
647,138
772,270
How can I download a utf-8-encoded web page with libcurl, preserving the encoding?
Im trying to get libcurl to download a webpage that is encoded in UTF-8, which is working fine, except for the fact that it converts it to ASCII and screws up some of the characters. Is there an easy way to get it to keep it in UTF-8?
libcurl doesn't translate/convert the data at all so there's actually nothing particular you need to do. Just get it.
647,413
647,424
what is the difference in using && and || in the do...while loop?
#include<iostream> using namespace std; int main() { char again; do { cout<<"you are in the while loop"; cout<<"do you want to continue looping?"; cin>>again; } while (again != 'n' || again != 'N'); system("pause"); return 0; } i know something is wrong with the test condition in the 'while'. But I can't figure it out. when the input of the user is neither 'n' nor 'N', the loop should keep on printing the code "you are in the while loop". Once 'n' or 'N' is pressed, the program will be terminated. However for my code, program will keep on looping the code regardless what character i enter. But when i change the '||' to '&&', the program can ran as desired. Anyone can tell me what is going on?
This is a common boolean logic question. || means "or," which means "as long as one side of this is true, then the expression is true." So when you pass an uppercase 'N' to c != 'n' || c != 'N' the program says "well, 'N' is not equal to 'n', therefore one side of the expression is true, therefore the whole expression is true and there is no need to check the rest of the expression." Even when you press lowercase 'n', the program says "well, 'n' is equal to 'n', but it's not equal to 'N', therefore one side of the expression is true, therefore the whole expression is true." This is what is happening in your while loop. On the other hand, && means "and" which means "both sides of the expression must be true"; when you pass an uppercase 'N' to c != 'n' && c != 'N' the program thinks "'N' is not equal to 'n', but it is equal to 'N', therefore only one side of the expression is true, therefore the expression is false." This gets confusing because if you were testing to see if the characters entered were equal to particular values you would use || (e.g., "I want to know if 'a' or 'b' or 'c' was entered"). Basically, when you would use || for a particular expression, and you want the opposite of that expression then you need to change to && (e.g., I want none of 'a', 'b' or 'c'; or to put it another way, the value cannot be 'a' and it cannot be 'b', and it cannot be 'c'"). Likewise, if you would use && for a particular expression, and you want the opposite of that expression then you need to use ||. This is one of De Morgan's laws, which I would recommend you read up on so you can avoid having to rediscover each of them on your own.
647,648
647,700
Is it better to store class constants in data members or in methods?
I recently wrote a class that renders B-spline curves. These curves are defined by a number of control points. Originally, I had intended to use eight control points, so I added a constant to the class, like so: class Curve { public: static const int CONTROL_POINT_COUNT = 8; }; Now I want to extend this class to allow an arbitrary amount of control points. So I want to change this to: class Curve { public: int getControlPointCount() {return _controlPointCount;} }; The question is whether it isn't better to store constants in methods to begin with, to facilitate adaptability. In other words, isn't it better to have started thus: class Curve { public: int getControlPointCount() {return 8;} }; The advantage of this is that I could have just changed one symbol in the method in question, instead of moving around constants etc. Is this a good practice or a bad one?
Typically I favour maintaining as few couplings manually as possible. The number of control points in the curve is, well, the number of control points in the curve. It's not an independent variable that can be set at will. So I usually would expose a const standard container reference: class Curve { private: std::vector<Point>& _controlPoints; public: Curve ( const std::vector<Point>& controlPoints) : _controlPoints(controlPoints) { } const std::vector<Point>& getControlPoints () { return _controlPoints; } }; And if you want to know how many control points, then use curve.getControlPoints().size(). I'd suspect that in most of the use cases you'd want the points as well as the count anyway, and by exposing a standard container you can use the standard library's iterator idioms and built-in algorithms, rather getting the count and calling a function like getControlPointWithIndex in a loop. If there really is nothing else in the curve class, I might even go as far as: typedef std::vector<Point> Curve; (often a curve won't render itself, as a renderer class can have details about the rendering pipeline, leaving a curve as purely the geometric artifact)
647,704
647,717
Why is getcwd() not ISO C++ compliant?
This MSDN article states that getcwd() has been deprecated and that the ISO C++ compatible _getcwd should be used instead, which raises the question: what makes getcwd() not ISO-compliant?
Functions not specified in the standard are supposed to be prefixed by an underscore as an indication that they're vendor-specific extensions or adhere to a non-ISO standard. Thus the "compliance" here was for Microsoft to add an underscore to the name of this specific function since it's not part of the ISO standard.
647,705
647,708
As a programmer with no CS degree, do I have to learn C++ extensively?
I'm a programmer with 2 years experience, I worked in 4 places and I really think of myself as a confident, and fluent developer. Most of my colleagues have CS degrees, and I don't really feel any difference! However, to keep up my mind on the same stream with these guys, I studied C (read beginning C from novice to professional), DataStructures with C, and also OOP with C++. I have a reasonable understanding of pointers, memory management, and I also attended a scholarship which C, DataStructures, and C++ were a part of it. I want to note that my familiarity with C and C++ does not exceed reading some pages, and executing some demos; I haven't worked on any project using C or C++. Lately a friend of mine advised me to learn C, and C++ extensively, and then move to OpenGL and learn about graphics programming. He said that the insights I may gain by learning these topics will really help me throughout my entire life as a programmer. PS: I work as a full-time developer mostly working on ASP.NET applications using C#. Recommendations?
For practical advancement: From a practical sense, pick a language that suites the domain you want to work in. There is no need to learn C nor C++ for most programming spaces. You can be a perfectly competent programmer without writing a line of code in those languages. If however you are not happy working in the exact field you are in now, you can learn C or C++ so that you may find a lower level programming job. Helping you be a better programmer: You can learn a lot from learning multiple languages though. So it is always good to broaden your horizons that way. If you want more experience in another language, and have not tried it yet, I would recommend to learn a functional programming language such as Scheme, Lisp, or Haskell.
647,796
648,088
How to figure out source line number from Linker Map
For some reason I have only the linker map for an application I am debugging. There is a crash log which says crash occurred at offset "myApp.exe! + 4CA24". From the linker map I am able to locate the method. Say this is at offset "myApp.exe! + 4BD7C". Is there anyway to figure out the exact line in source code using just the above info? I know if we have a .cod file it makes it very easy, but I don't have one (and can't create).
The best you can do if you only have MAP-files is to study the EXE-file in a disassembler and compare to constructs that you recognize from the common ways the compiler generates code. These you have to learn. That means learning at least some assembler is required. This is good knowledge that will help you in the future, especially if you have to debug a lot of code. A slightly simpler approach is to download the free Intel-books on processor instructions and simply check out their sizes. This way you can count your way to the faulting instruction. For best results the two methods should be used in conjunction with each other. Typically what you'd be looking for is something that looks a bit like this: mov DWORD PTR [edi+40], eax (Instruction, register, offset, size and order can be different but indirection is typically where most code crashes) Whatever you do you should seriously consider turning on COD-file generation for the future as that makes it super-easy to find the faulting line.
647,967
647,977
How to extend std::tr1::hash for custom types?
How do I allow the STL implementation to pick up my custom types? On MSVC, there is a class std::tr1::hash, which I can partially specialize by using namespace std { namespace tr1 { template <> struct hash<MyType> { ... }; } } but is this the recommended way? Moreover, does this work with GCC's implementation as well? For boost::hash, it's enough to provide a free function size_t hash_value (const MyType&), is there something similar for the TR1 implementation?
Yes, this will also work for GCC. I'm using it in a bigger project and it works without problems. You could also provide your own custom hashing class for the TR1 containers, but it is specified that std::tr1::hash<> is the default hashing class. Specializing it for custom types seems like the natural way to extend the standard hashing functionality.
647,988
647,997
Why can't I assign values to pointers?
After reading the faq's and everything else I can find, I'm still confused. If I have a char pointer that is initialised in this fashion: char *s = "Hello world!" The string is in read-only memory and I cannot change it like this: *s = 'W'; to make "Wello world!". This I understand, but I can't, for the life of me, understand how to make it NOT read-only. Do I have to use an array instead of a pointer? Like here? This is my code: char *s = str; char *e = s; while (*e != '\0') e++; e--; char *temp; //Swop the string around while (s <= e) { *temp = *s; *s = *e; *e = *temp; e--; s++; } The error message is just a segmentation fault. Apologies in advance if this is a really stupid question. Thanks so much for all the help. After taking all your advice, I get this: void something(char * str) { char *store = str; char *s = new char[strlen(str) + 1]; //Allocate memory. Nice one. strcpy(s, str); char *e = new char[strlen(str) + 1]; strcpy(e, str); while (*e != '\0') e++; e--; char temp; //no longer a pointer while (s <= e) { cout << *e; temp = *s; *s = *e; *e = temp; e--; s++; } delete [] e; delete [] s; } however, the deletes at the end of the function seem to be causing their own segmentation faults. Why? For interest's sake: The faults were due to accessing the e and s pointers after they were incremented. A much simpler solution followed from that: void something(char * str) { char *s = new char[strlen(str) + 1]; strcpy(s, str); char temp; int j = strlen(str) - 1; for (int i = 0; i <= strlen(str)/2; i++) { cout << s << endl; temp = s[i]; s[i] = s[j]; s[j] = temp; j--; } delete [] s; }
The easiest way to modify it is to create an array for your storage, and then copy the string into it. For example: char buf[128]; const char *src = "Hello World"; strncpy(buf, src, 127); // one less - we always 0-terminate buf[127] = '\0'; // you can now modify buf buf[0] = 'W'; The reason your code doesn't work is that you haven't allocated any memory for the copy of the string - you've just made a second pointer to the same read-only memory. (And then tried to copy it? I'm not quite sure what the rest of the code is doing.) You need to get some non-read-only memory somewhere, and it's much easier to use the standard library to copy it into that new memory, rather than writing the loop yourself. In the case when you don't know the length of the string beforehand, you can also use malloc (or, even better, do what drschnz's answer says and use new char[]): const char *src = "Hello world"; char *buf = malloc(strlen(src) + 1); // or = new char[strlen(src) + 1]; strcpy(buf, src); // you can now modify buf // later, you need to free it free(buf); // or delete [] buf; Also, if you're using C++, you can just use a std::string: std::string myString("Hello world"); myString[0] = "W"; Hope that helps.
648,138
648,202
HELP VS8 Command line to IDE?
PROBLEM: C:\>cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /link/out:hello.dll 'cl' is not recognized as an internal or external command, operable program or batch file. I am using Visual Studio Prof Edi 2008. What PATH should I set for this command to work? How to execute above command using the IDE? NOTE:I am studying this. C:\>cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /li nk/out:hello.dll 'cl' is not recognized as an internal or external command, operable program or batch file. C:\>PATH="C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe" C:\>cl 'cl' is not recognized as an internal or external command, operable program or batch file. C:\>PATH="C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe" C:\>cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /li nk/out:hello.dll 'cl' is not recognized as an internal or external command, operable program or batch file. C:\>
You can set up the environment by using C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat
648,334
648,345
Should I learn GTK+ or GTKMM?
I am a C# programmer who started using ubuntu about 2 years ago. I'm wanting to learn GUI programming in either C or C++. I don't really like mono, it tends to crash on my system. I have a basic understanding of C++. I have never worked in C, but it looks cool. Which toolkit should I learn/use? Give Pro/Cons of each. Thanks!
Since C++ is more familiar to you, you may find GTKmm to be a better fit, since you can use idioms like RAII. Unfortunately, GTKmm is a little incomplete and is missing a few of the lesser-used parts of GTK. GTK+ on its own, however, essentially exposes an object model similar to what you find in C++, but with only C functions. Things like construction and destruction in C++ are done explicitly in the C API and instances of widgets are handled via pointers exclusively. Try both and see which fits your project better.
648,380
648,442
Evaluation order of new expression?
In the following code sample, do the C++ standard guarantee that '++i' is evaluated after the memory allocation (call to operator new) but before the call to X’s constructor? new X( ++i )
From my copy of n2798: 5.3.4 New 21 Whether the allocation function is called before evaluating the constructor arguments or after evaluating the constructor arguments but before entering the constructor is unspecified. It is also unspecified whether the arguments to a constructor are evaluated if the allocation function returns the null pointer or exits using an exception. Read in conjunction with (to avoid ambiguities): 5.3.4 New 8 A new-expression obtains storage for the object by calling an allocation function (3.7.4.1). If the newexpression terminates by throwing an exception, it may release storage by calling a deallocation function (3.7.4.2). If the allocated type is a non-array type, the allocation function’s name is operator new and the deallocation function’s name is operator delete. If the allocated type is an array type, the allocation function’s name is operator new[] and the deallocation function’s name is operator delete[]. [...] This pretty much answers the question. The answer is 'No'.
648,464
648,465
Why does g++ compile this?
Recently, after being very tired, I wrote the following code: GLfloat* array = new GLfloat(x * y * z); Which, of course should have been: GLfloat* array = new GLfloat[x * y * z]; (Note the square brackets as opposed to the parenthesis.) As far as I know, the first form is not valid, but g++ compiled it. Sure, it spat out a completely incomprehensible segfault, but it compiled. Why?
GLfloat* array = new GLfloat(x * y * z); Creates a pointer called array to an object of type GLfloat with a value of x * y * z.
648,545
648,550
How to perform fast formatted input from a stream in C++?
The situation is: there is a file with 14 294 508 unsigned integers and 13 994 397 floating-point numbers (need to read doubles). Total file size is ~250 MB. Using std::istream takes ~30sec. Reading the data from file to memory (just copying bytes, without formatted input) is much faster. Is there any way to improve reading speed without changing file format?
Do you need to use STL style i/o? You must check out this excellent piece of work from one of the experts. It's a specialized iostream by Dietmar Kuhl. I hate to suggest this but take a look at the C formatted i/o routines. Also, are you reading in the whole file in one go?
648,619
648,629
Resizing an OpenGL window causes it to fall apart
For some reason when I resize my OpenGL windows, everything falls apart. The image is distorted, the coordinates don't work, and everything simply falls apart. I am sing Glut to set it up. //Code to setup glut glutInitWindowSize(appWidth, appHeight); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutCreateWindow("Test Window"); //In drawing function glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClear(GL_COLOR_BUFFER_BIT); //Resize function void resize(int w, int h) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, w, h, 0); } The OpenGL application is strictly 2D. This is how it looks like initially: http://www.picgarage.net/images/Corre_53880_651.jpeg this is how it looks like after resizing: http://www.picgarage.net/images/wrong_53885_268.jpeg
You should not forget to hook the GLUT 'reshape' event: glutReshapeFunc(resize); And reset your viewport: void resize(int w, int h) { glViewport(0, 0, width, height); //NEW glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, w, h, 0); } A perspective projection would have to take the new aspect ratio into account: void resizeWindow(int width, int height) { double asratio; if (height == 0) height = 1; //to avoid divide-by-zero asratio = width / (double) height; glViewport(0, 0, width, height); //adjust GL viewport glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(FOV, asratio, ZMIN, ZMAX); //adjust perspective glMatrixMode(GL_MODELVIEW); }
648,647
648,661
In C++, where in memory are class functions put?
I'm trying to understand what kind of memory hit I'll incur by creating a large array of objects. I know that each object - when created - will be given space in the HEAP for member variables, and I think that all the code for every function that belongs to that type of object exists in the code segment in memory - permanently. Is that right? So if I create 100 objects in C++, I can estimate that I will need space for all the member variables that object owns multiplied by 100 (possible alignment issues here), and then I need space in the code segment for a single copy of the code for each member function for that type of object( not 100 copies of the code ). Do virtual functions, polymorphism, inheritance factor into this somehow? What about objects from dynamically linked libraries? I assume dlls get their own stack, heap, code and data segments. Simple example (may not be syntactically correct): // parent class class Bar { public: Bar() {}; ~Bar() {}; // pure virtual function virtual void doSomething() = 0; protected: // a protected variable int mProtectedVar; } // our object class that we'll create multiple instances of class Foo : public Bar { public: Foo() {}; ~Foo() {}; // implement pure virtual function void doSomething() { mPrivate = 0; } // a couple public functions int getPrivateVar() { return mPrivate; } void setPrivateVar(int v) { mPrivate = v; } // a couple public variables int mPublicVar; char mPublicVar2; private: // a couple private variables int mPrivate; char mPrivateVar2; } About how much memory should 100 dynamically allocated objects of type Foo take including room for the code and all variables?
It's not necessarily true that "each object - when created - will be given space in the HEAP for member variables". Each object you create will take some nonzero space somewhere for its member variables, but where is up to how you allocate the object itself. If the object has automatic (stack) allocation, so too will its data members. If the object is allocated on the free store (heap), so too will be its data members. After all, what is the allocation of an object other than that of its data members? If a stack-allocated object contains a pointer or other type which is then used to allocate on the heap, that allocation will occur on the heap regardless of where the object itself was created. For objects with virtual functions, each will have a vtable pointer allocated as if it were an explicitly-declared data member within the class. As for member functions, the code for those is likely no different from free-function code in terms of where it goes in the executable image. After all, a member function is basically a free function with an implicit "this" pointer as its first argument. Inheritance doesn't change much of anything. I'm not sure what you mean about DLLs getting their own stack. A DLL is not a program, and should have no need for a stack (or heap), as objects it allocates are always allocated in the context of a program which has its own stack and heap. That there would be code (text) and data segments in a DLL does make sense, though I am not expert in the implementation of such things on Windows (which I assume you're using given your terminology).
648,888
648,963
How to pass references by value in C++?
I'm trying to create am immutable type (class) in C++, I made it so that all methods "aka member functions" don't modify the object and return a new instance instead. I'm running across a bunch of issues, but they all revolve around the reference types in C++. One example is when passing parameters of the same class type by reference: Imm Imm::someOp( const Imm& p_im ) const { ... p_im = p_im.someOtherOp(); //error, p_im is const, can't modify it! ... } The error is caused by passing the value by reference. If instead, I was passing the reference by value, then the error line above would not be an error! Consider a Java/C# example class Imm { ... Imm someOp( Imm p_im ) { .... p_im = p_im.someOtherOp(); //ok, you're not modifying the //original object, just changing the local reference .... } .... } How can I do something like this in C++? I know I can use pointers but then I run into the whole memory management mess. I don't want to worry about who owns references to objects. Ideally I'd like to design the class to be like immutable strings in python; you can use them without ever noticing or even knowing that they're immutable, and they just behave as you expect; they just work. EDIT Of course I can get around it by passing-by-value or by using a temp variable (which is what I'm doing currently). What I'm asking about is "how to pass references by value in C++" I'm expecting the answer to revolve around something in the STL, I'm currently looking into smart_ptr family of templates. UPDATE Thanks for the responses, I realize there's no escape from pointers. (see my other question, which is really a follow up on this one)
In Java and C#, you are not really dealing with a reference - they are more like handles or pointers. A reference in C++ is really another name for the original object, not a pointer to it (although it may be implemented with a pointer). When you assign a value to a reference, you are assigning to the object itself. There is confusion in that to initialize a reference you can use the = character, but it is an initialization, not an assignment. Imm im, im2, im3; Imm &imr = im; // initialize a reference to im imr = im2; // assign im2 to imr (changes the value of im as well) Imm *imp = &im; // initialize a pointer to the address of im imp = &im3; // assign the address of im3 to imp (im is unnaffected); (*imp) = im2; // assign im2 to imp (modifies im3 as well). If you specifically want to pass "references by value" then you are essentially asking for a contradition in terms. References, by definition are passed by reference. As pointed out elsewhere, you can pass a pointer by value, or else a straight value. If you really want, you can hold onto a reference in a class and pass that around by value: struct ImmRef { Imm &Ref; ImmRef(Imm &ref) : Ref(ref) {} }; Note also that a const applied to a reference is making the referred to object constant, not the reference. References are always const.
648,900
648,905
C++ templates, undefined reference
I have a function declared like so: template <typename T> T read(); and defined like so: template <typename T> T packetreader::read() { offset += sizeof(T); return *(T*)(buf+offset-sizeof(T)); } However, when I try to use it in my main() function: packetreader reader; reader.read<int>(); I get the following error from g++: g++ -o main main.o packet.o main.o: In function `main': main.cpp:(.text+0xcc): undefined reference to `int packetreader::read<int>()' collect2: ld returned 1 exit status make: *** [main] Error 1 Can anyone point me into the right direction?
You need to use the export keyword. However, I don't think G++ has proper support, so you need to include the template function's definition in the header so the translation unit can use it. This is because the <int> 'version' of the template hasn't been created, only the <typename T> 'version.' An easy way is to #include the .cpp file. However, this can cause problems, e.g. when other functions are in the .cpp file. It will also likely increase the compile time. A clean way is to move your template functions into its own .cpp file, and include that in the header or use the export keyword and compile it separately. More information on why you should try and put template function definitions in its header file (and ignore export altogether).
648,917
648,937
Can I use execvp() on a function defined inside my program?
I have a C++ function that I'd like to call using execvp(), due to the way my program is organized. Is this possible?
All of the exec variants including execvp() can only call complete programs visible in the filesystem. The good news is that if you want to call a function in your already loaded program, all you need is fork(). It will look something like this pseudo-code: int pid = fork(); if (pid == 0) { // Call your function here. This is a new process and any // changes you make will not be reflected back into the parent // variables. Be careful with files and shared resources like // database connections. _exit(0); } else if (pid == -1) { // An error happened and the fork() failed. This is a very rare // error, but you must handle it. } else { // Wait for the child to finish. You can use a signal handler // to catch it later if the child will take a long time. waitpid(pid, ...); }
648,960
649,071
std::vector on VisualStudio2008 appears to be suboptimally implemented - too many copy constructor calls
I've been comparing a STL implementation of a popular XmlRpc library with an implementation that mostly avoids STL. The STL implementation is much slower - I got 47s down to 4.5s. I've diagnosed some of the reasons: it's partly due to std::string being mis-used (e.g. the author should have used "const std::string&" wherever possible - don't just use std::string's as if they were Java strings), but it's also because copy constructors were being constantly called each time the vector outgrew its bounds, which was exceedingly often. The copy constructors were very slow because they did deep-copies of trees (of XmlRpc values). I was told by someone else on StackOverflow that std::vector implementations typically double the size of the buffer each time they outgrow. This does not seem to be the case on VisualStudio 2008: to add 50 items to a std::vector took 177 calls of the copy constructor. Doubling each time should call the copy constructor 64 times. If you were very concerned about keeping memory usage low, then increasing by 50% each time should call the copy constructor 121 times. So where does the 177 come from? My question is: (a) why is the copy constructor called so often? (b) is there any way to avoid using the copy constructor if you're just moving an object from one location to another? (In this case and indeed most cases a memcpy() would have sufficed - and this makes a BIG difference). (NB: I know about vector::reserve(), I'm just a bit disappointed that application programmers would need to implement the doubling trick when something like this is already part of any good STL implementation.) My test program: #include <string> #include <iostream> #include <vector> using namespace std; int constructorCalls; int assignmentCalls; int copyCalls; class C { int n; public: C(int _n) { n = _n; constructorCalls++; } C(const C& orig) { copyCalls++; n = orig.n; } void operator=(const C &orig) { assignmentCalls++; n = orig.n; } }; int main(int argc, char* argv[]) { std::vector<C> A; //A.reserve(50); for (int i=0; i < 50; i++) A.push_back(i); cout << "constructor calls = " << constructorCalls << "\n"; cout << "assignment calls = " << assignmentCalls << "\n"; cout << "copy calls = " << copyCalls << "\n"; return 0; }
The STL does tend to cause this sort of thing. The spec doesn't allow memcpy'ing because that doesn't work in all cases. There's a document describing EASTL, a bunch of alterations made by EA to make it more suitable for their purposes, which does have a method of declaring that a type is safe to memcpy. Unfortunately it's not open source AFAIK so we can't play with it. IIRC Dinkumware STL (the one in VS) grows vectors by 50% each time. However, doing a series of push_back's on a vector is a common inefficiency. You can either use reserve to alleviate it (at the cost of possibly wasting memory if you overestimate significantly) or use a different container - deque performs better for a series of insertions like that but is a little slower in random access, which may/may not be a good tradeoff for you. Or you could look at storing pointers instead of values which will make the resizing much cheaper if you're storing large elements. If you're storing large objects this will always win because you don't have to copy them ever - you'll always save that one copy for each item on insertion at least.
648,998
649,035
Is C++ a "waste of time"?
I ran into this supposed interview of Bjarne Stroustrup, the inventor of C++. http://artlung.com/smorgasborg/Invention_of_Cplusplus.shtml Stroustrup: Well, it's been long enough, now, and I believe most people have figured out for themselves that C++ is a waste of time but, I must say, it's taken them a lot longer than I thought it would... Interviewer: Yes, but C++ is basically a sound language. Stroustrup: You really believe that, don't you? Have you ever sat down and worked on a C++ project? Here's what happens: First, I've put in enough pitfalls to make sure that only the most trivial projects will work first time. Take operator overloading. At the end of the project, almost every module has it, usually, because guys feel they really should do it, as it was in their training course. The same operator then means something totally different in every module. Try pulling that lot together, when you have a hundred or so modules. And as for data hiding, God, I sometimes can't help laughing when I hear about the problems companies have making their modules talk to each other. Is this a hoax? Do any of these points seem true for any of the veteran C++ programmers out there?
You just have to check the Stroustrup's website (the FAQ part) to find that it's wrong - a well known hoax as Judah Himango already pointed : Did you really give an interview to IEEE? in which you confessed that C++ was deliberately created as an awful language for writing unmaintainable code to increase programmers' salaries? Of course not. Read the real IEEE interview.
649,618
650,615
How to Build a custom simple DNS server in C/C++
I need to build a custom simple non-authoritative caching DNS server in C/C++. Any guidance? Links? Samples?
There's no such thing as a "simple" cacheing DNS server, particularly if you want decent security. Recent DNS attacks have shown that the cacheing function in recursive DNS servers is particularly vulnerable. Re-evaluate whether you actually need local cacheing of your own. If you don't, you're probably better off modifying existing DNS proxy code (such as 'dnsmasq'). If you do want to roll-your-own, there are good libraries such as ldns which can provide the access to the underlying DNS packets. I'm using ldns myself in conjunction with libevent to implement the Fuzzing DNS server I mentioned in an earlier question.
649,640
649,709
How to do an efficient priority update in STL priority_queue?
I have a priority_queue of some object: typedef priority_queue<Object> Queue; Queue queue; From time to time, the priority of one of the objects may change - I need to be able to update the priority of that object in the queue in an efficient way. Currently I am using this method which works but seems inefficient: Queue newQueue; while (!queue.empty()) { Object obj=queue.top(); queue.pop(); if (priorityHasChanged(obj)) newQueue.push_back(Object(new_priority)); else newQueue.push_back(obj); } newQueue.swap(queue); // this only works because I actually subclassed the priority_queue // class and exposed a swap method that swaps in the container I implemented it this way because I was in kind of a hurry at the time and this was the quickest thing I could do that I could be sure it would work ok. There has to be a better way than this though. Really what I want is a way to either: extract out the instance with the changed priority and insert a new one with the new priority value update the instance with the changed priority and then update the queue so that it is correctly sorted What is the best way to do this?
I think you are out of luck with standard priority queue because you can't get at the underlying deque/vector/list or whatever. You need to implement your own - it's not that hard.
649,789
650,533
What would be C++ limitations compared C language?
Following are the benefits of C++ C++ provides the specific features they are asking about Their C compiler is almost certainly really a C++ compiler, so there are no software cost implications C++ is just as portable as C C++ code can be just as efficient as C (or more so, or less so) Are there any concrete reasons and specific scenarios, where one has to use C over C++? Reference to this question:Library for generics in C Not a duplicate, because this question is asking about language limitations and not about should/shouldn't learn one language over another. Peter Kirkham's post was for me the most informative, particularly with regard to C99 issues which I hadn't considered, so I've accepted it. Thanks to all others who took part.
This is prompted by a an answer I gave to a current question which asks about a generics library for C - the questioner specifically states that they do not want to use C++. C is a complete programming language. C is not an arbitrary subset of C++. C is not a subset of C++ at all. This is valid C: foo_t* foo = malloc ( sizeof(foo_t) ); To make it compile as C++ you have to write: foo_t* foo = static_cast<foo_t*>( malloc ( sizeof(foo_t) ) ); which isn't valid C any more. (you could use the C-style cast, it which case it would compile in C, but be shunned by most C++ coding standards, and also by many C programmers; witness the "don't cast malloc" comments all over Stack Overflow). They are not the same language, and if you have an existing project in C you don't want to rewrite it in a different language just to use a library. You would prefer to use libraries which you can interface to in the language you are working in. (In some cases this is possible with a few extern "C" wrapper functions, depending on how template/inline a C++ library is.) Taking the first C file in a project I'm working on, this is what happens if you just swap gcc std=c99 for g++: sandiego:$ g++ -g -O1 -pedantic -mfpmath=sse -DUSE_SSE2 -DUSE_XMM3 -I src/core -L /usr/lib -DARCH=elf64 -D_BSD_SOURCE -DPOSIX -D_ISOC99_SOURCE -D_POSIX_C_SOURCE=200112L -Wall -Wextra -Wwrite-strings -Wredundant-decls -Werror -Isrc src/core/kin_object.c -c -o obj/kin_object.o | wc -l In file included from src/core/kin_object.c:22: src/core/kin_object.h:791:28: error: anonymous variadic macros were introduced in C99 In file included from src/core/kin_object.c:26: src/core/kin_log.h:42:42: error: anonymous variadic macros were introduced in C99 src/core/kin_log.h:94:29: error: anonymous variadic macros were introduced in C99 ... cc1plus: warnings being treated as errors src/core/kin_object.c:101: error: ISO C++ does not support the ‘z’ printf length modifier .. src/core/kin_object.c:160: error: invalid conversion from ‘void*’ to ‘kin_object_t*’ .. src/core/kin_object.c:227: error: unused parameter ‘restrict’ .. src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier In total 69 lines of errors, four of which are invalid conversions, but mostly for features that exist in C99 but not in C++. It's not like I'm using those features for the fun of it. It would take significant work to port it to a different language. So it is plain wrong to suggest that [a] C compiler is almost certainly really a C++ compiler, so there are no software cost implications There are often significant cost implications in porting existing C code to the procedural subset of C++. So suggesting 'use the C++ std::queue class' as an answer to question looking for an library implementation of a queue in C is dafter than suggesting 'use objective C' and 'call the Java java.util.Queue class using JNI' or 'call the CPython library' - Objective C actually is a proper superset of C (including C99), and Java and CPython libraries both are callable directly from C without having to port unrelated code to the C++ language. Of course you could supply a C façade to the C++ library, but once you're doing that C++ is no different to Java or Python.
649,793
649,861
Howto Create Map of Vector From Sorted Data
I have the following data as input (sorted by first column): foo 1 2 foo 3 3 bar 10 11 I want to create a Map of Vector with first column as key of the map such that we have: foo = {1,2,3,3} bar = {10,11} But why my code below doesn't work as expected? #include <vector> #include <map> #include <iostream> #include <fstream> #include <sstream> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count !=2 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } string line; ifstream acemblyfile (arg_vec[1]); map <string, vector<int> > myMapOfVec; vector <string> myVec; string KEY = "" ; if (acemblyfile.is_open()) { while (getline(acemblyfile,line) ) { stringstream ss(line); string KEY_TEMP; int VAL1; int VAL2; ss >> KEY_TEMP >> VAL1 >> VAL2; MyVec.push_back(VAL1); MyVec.push_back(VAL2); if (KEY_TEMP != KEY) { myMapOfVec[KEY] = MyVec; KEY = KEY_TEMP; MyVec.clear(); } } acemblyfile.close(); } else { cout << "Unable to open file"; } for( map<string, vector<int> >::iterator iter = myMapOfVec.begin(); iter != myMapOfVec.end(); ++iter ) { vector <int> tempVec = (*iter).second; string Key = (*iter).first; for (unsigned i =0; i<tempVec.size(); i++) { cout << Key << " " << tempVec[i] << endl; } } return 0; }
As Mykola said, you should use the vector in the map instead of creating one yourself. I changed your whole code so it works for me. Note that you wrote some of the variable names with wrong case (MyMapOfVec instead of myMapOfVec) and this led to compiler errors. Also be sure you don't have a newline at the end of your input file because this will result in repeating the last line. #include <vector> #include <map> #include <iostream> #include <fstream> #include <sstream> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count !=2 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } string line; ifstream acemblyfile (arg_vec[1]); map <string, vector<int> > myMapOfVec; string KEY; if (acemblyfile.is_open()) { while (getline(acemblyfile, line) ) { stringstream ss(line); int VAL1; int VAL2; ss >> KEY >> VAL1 >> VAL2; myMapOfVec[KEY].push_back(VAL1); myMapOfVec[KEY].push_back(VAL2); } acemblyfile.close(); } else { cout << "Unable to open file"; } for( map<string, vector<int> >::iterator iter = myMapOfVec.begin(); iter != myMapOfVec.end(); ++iter ) { vector<int> tempVec = (*iter).second; string Key = (*iter).first; cout << Key; for (unsigned i = 0; i < tempVec.size(); i++) { cout << " " << tempVec[i]; } cout << endl; } return 0; } For your example, this gives the output bar 10 11 foo 1 2 3 3
649,855
649,883
What is the point of adding a return statement at end of a void C/C++ routine?
I see functions/methods with a void return in the signature that have a return statement at the end of the function. What is the reason for this, and does this apply to other languages? For all I know, I can use return if I want to exit anywhere else but the end of the function. A C example: void function(void) { int x = 1 + 2; return; // what do we need this for, if at all? }
This seems pointless here. But my guess is that this kind of thing can be used to put a breakpoint in IDEs which don't support putting a breakpoint at the closing brace and by putting a breakpoint here, some values can be checked in the watch window etc.
649,886
649,906
How can you break on handle creation?
I have an application that spawns multiple child processes. Before launching a child, I create stdOut and stdErr handles to a log file (for example, if I am about to launch procA, i create handles to logA.log). I set these handles on the child processes. By looking with ProcExplorer, I can see that each child process has handles to each log file (so procA has handles to logA, logB, etc.). This is creates later problems. I want to be able to see when procA creates the handle to logB. Any ideeas?
One possible solution can be that handle to file are shared between any child processes beacause they are created by the parent process. That's the only solution I can see because I don't see how you can have multpile handle (one to each log file) in each child processes if you design so that you only have one var to handle it. Why not creating your handles in the child processes ? I know it does respond pricesly to the question but obviously if procA only need the handles to logA it will better to create the handle to logA in the child process procA.
649,900
649,946
Detecting the launch of a application
How do I detect with C# on Windows the moment when an external application is being launched? I tried the FilesystemWatcher which doesn't work because the file is not really changing. Also having a timer constantly check all the open processes might be a bit over kill. Is there any other way to do this? If not in C# is it possible to do so in C++ (if so please give me an example). The reason I want to do this is for logging purposes.
You can use System.Management and WMI (Windows Management Instrumentation) class WMIEvent { public static void Main() { WMIEvent we = new WMIEvent(); ManagementEventWatcher w= null; WqlEventQuery q; try { q = new WqlEventQuery(); q.EventClassName = "Win32_ProcessStartTrace"; w = new ManagementEventWatcher(q); w.EventArrived += new EventArrivedEventHandler(we.ProcessStartEventArrived); w.Start(); Console.ReadLine(); // block main thread for test purposes } finally { w.Stop(); } } public void ProcessStartEventArrived(object sender, EventArrivedEventArgs e) { foreach(PropertyData pd in e.NewEvent.Properties) { Console.WriteLine("\n============================= ========="); Console.WriteLine("{0},{1},{2}",pd.Name, pd.Type, pd.Value); } }
650,091
650,142
Using an abstract class in C++
I'm trying to use an abstract class when passing an extended object as an parameter to a function, but my attempts so far have led to some compiler errors. I have a few clues as to what the problem is, I'm obviously not allowed to instantiate an abstract class, and I believe some of the code in MyClass is trying to do this, even though this is not my intention. Some researching has suggested that I should reference the object as a pointer to achieve what I want, but my attempts so far have failed and I'm not even sure that this is the answer (hence my asking here). I'll submit now that I'm more familiar with Java than C++, and I'm sure part of my problem is due to this. Here is an example of what I'm trying to do in my program: class A { public: virtual void action() = 0; }; class B : public A { public: B() {} void action() { // Do stuff } }; class MyClass { public: void setInstance(A newInstance) { instance = newInstance; } void doSomething() { instance.action(); } private: A instance; }; int main(int argc, char** argv) { MyClass c; B myInstance; c.setInstance(myInstance); c.doSomething(); return 0; } This example produces the same compiler error that I am getting in my program: sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp test.cpp:20: error: cannot declare parameter ‘newInstance’ to be of abstract type ‘A’ test.cpp:2: note: because the following virtual functions are pure within ‘A’: test.cpp:4: note: virtual void A::action() test.cpp:30: error: cannot declare field ‘MyClass::instance’ to be of abstract type ‘A’ test.cpp:2: note: since type ‘A’ has pure virtual functions test.cpp: In function ‘int main(int, char**)’: test.cpp:36: error: cannot allocate an object of abstract type ‘A’ test.cpp:2: note: since type ‘A’ has pure virtual functions Update Thanks for the feedback everyone. I've since changed "MyClass::instance to contain a pointer of type A, but I now get some bizarre errors related to the vtable: sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp /tmp/ccoEdRxq.o:(.rodata._ZTI1B[typeinfo for B]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info' /tmp/ccoEdRxq.o:(.rodata._ZTI1A[typeinfo for A]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info' /tmp/ccoEdRxq.o:(.rodata._ZTV1A[vtable for A]+0x8): undefined reference to `__cxa_pure_virtual' collect2: ld returned 1 exit status My modified code is as follows (A and B have not been modified): class MyClass { public: void setInstance(A* newInstance) { instance = newInstance; } void doSomething() { instance->action(); } private: A* instance; }; int main(int argc, char** argv) { MyClass c; B myInstance; c.setInstance(&myInstance); c.doSomething(); return 0; }
Your problem is that you should accept a reference in your function. The reason is that a reference does not actually copy the argument passed. If you however accept an A - instead of a reference A& - then you actually copy the argument passed into the parameter object, and what you get is an object of type A - but which is actually not allowed! // the reference parameter will reference the actual argument void setInstance(A &newInstance) { // assign the address of the argument to the pointer member // instance. instance = &newInstance; } And then you will have to change the member in your class to be a pointer. It can't be a reference because setInstance will change what it references - a reference can only reference one object during its entire lifetime, while a pointer can be set to point do different things just by reassigning it a different address. The remaining parts look like this then void doSomething() { // call a member function on the object pointed to // by instance! instance->action(); } private: // a pointer to some object derived from A A *instance; Also note that you have to compile C++ programs using g++, because it additionally links the C++ standard library to your code g++ -o test test.cpp # instead of gcc!
650,162
650,218
Why can't the switch statement be applied to strings?
Compiling the following code gives the error message: type illegal. int main() { // Compilation error - switch expression of type illegal switch(std::string("raj")) { case"sda": } } You cannot use string in either switch or case. Why? Is there any solution that works nicely to support logic similar to switch on strings?
The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string. In order to generate the code for a switch statement the compiler must understand what it means for two values to be equal. For items like ints and enums, this is a trivial bit comparison. But how should the compiler compare 2 string values? Case sensitive, insensitive, culture aware, etc ... Without a full awareness of a string this cannot be accurately answered. Additionally, C/C++ switch statements are typically generated as branch tables. It's not nearly as easy to generate a branch table for a string style switch.
650,232
650,237
Using a pointer to an object stored in a vector... c++
I have a vector of myObjects in global scope. std::vector<myObject> A method is passed a pointer to one of the elements in the vector. Can this method increment the pointer, to get to the next element, myObject* pmObj; ++pmObj; // the next element ?? or should it be passed an std::Vector<myObject>::iterator and increment that instead? Assume for now that the vector will not get changed in the meantime.
Yes - the standard guarantees in a technical correction that the storage for a vector is contiguous, so incrementing pointers into a vector will work.
650,261
650,276
C++ ULONG definitions to VB.NET or C# equivalent?
I am trying to use a call-recording API using sockets. We have the API documentation, but the samples are all in C++. How would I declare the following in VB.NET or C#? #define SIF_GENERAL 0x08000000 #define SIF_CONFIGURATION 0x08010000 #define SIF_ARCHIVE 0x08020000 #define SIF_SEARCH 0x08030000 #define SIF_REPLAY 0x08040000 #define SIF_STATISTICS 0x08050000 #define SIF_ENGINEER 0x08060000 Note from the documentation: message identifiers are unsigned 32-bit values (ULONG).
VB.NET Module Constants Public Const SIF_GENERAL as Integer =&H08000000 Public Const SIF_CONFIGURATION As Integer = &H08010000 Public Const SIF_ARCHIVE As Integer = &H08020000 Public Const SIF_SEARCH As Integer = &H08030000 Public Const SIF_REPLAY As Integer = &H08040000 Public Const SIF_STATISTICS As Integer = &h08050000 Public Const SIF_ENGINEER As Integer = &h08060000 End Module C# public static class Constants { public const int SIF_GENERAL =0x08000000; public const int SIF_CONFIGURATION = 0x08010000; public const int SIF_ARCHIVE = 0x08020000; public const int SIF_SEARCH = 0x08030000; public const int SIF_REPLAY = 0x08040000; public const int SIF_STATISTICS = 0x08050000; public const int SIF_ENGINEER = 0x08060000; }
650,283
650,301
Duplicating arrays when equalizing Objects
Greetings everyone. I'm in need of some experiance here as how to deal with dynamic arrays with Objects. I've a class 'SA', consisting of several objects 'Obj1', 'Obj2' etc... Within the class I have a dynamic array 'SA_Array' which I initialize in the following manner where size sets its length: double * SA_Array; SA_Array = new double [size]; Now I've been trying to use the '=' operator on the above objects to make copies of the array in each object. Unfortunatly I've realised that it only equalizes the pointer and hence if I modify the array in one object, all the object SA_Array's are modified the same... Essentially leaving me with only one copy on the array. e.g. Obj1.SA_Array == Obj2.SA_Array... Are there any good suggestions as to how to overcome this and achieve object specific copies of SA_Array?
If the size is determined at runtime, easiest to use one is a vector vector<double> SA_Array(size); Now you can copy, swap, resize it and it will act accordingly. If you need a pointer to the begin, you can do that with &SA_Array[0]. If the size is determined and fixed at compile time, you can use boost::array boost::array<double, size> SA_Array; You can use it like an array, but can also copy it and do stuff like SA_Array.begin() like with the vector. If you need a pointer to the begin, you can do that with SA_Array.data() or &SA_Array[0]. There is the way using raw pointers too like you did, and copying it manually double *SA_Array; SA_Array = new double[size]; double *SA_Copy; SA_Copy = new double[size]; std::copy(SA_Array, SA_Array + size, SA_Copy); But it is cumbersome as you will need to remember to delete[] them, which a vector will do all for you.
650,309
682,876
How to inhib "Delayed Write Failed" message?
I have a Windows service running in a specified user account with write permission on a shared drive on another computer. The service is logging on that shared drive. I allow the user to enter mapped path or network path (e.g. z:\MyRemoteFolder or \RemoteComputer\MyRemoteFolder) as the log destination. As I am in an unstable network environment, I sometime see the error "Windows - Delayed Write Failed". I know you can disable caching in a per drive basis (including mapped drive), but is there a way to disable caching for any direct access network (\RemoteComputer\MyRemoteFolder)? Thanks a lot, Nic
Using "FILE_FLAG_WRITE_THROUGH" and "FILE_FLAG_NO_BUFFERING" in create file worked for me.
650,461
650,711
What are some tricks I can use with macros?
In our legacy code, as well as our modern code, we use macros to perform nifty solutions like code generations, etc. And we make use of both the # and ## operators. I am curious how other developers use macros to do cool things, if they use them at all.
In C, it's common to define macros that do some stuff getting the verbatim argument, and at the same time define functions to be able to get the address of it transparently. // could evaluate at compile time if __builtin_sin gets // special treatment by the compiler #define sin(x) __builtin_sin(x) // parentheses avoid substitution by the macro double (sin)(double arg) { return sin(arg); // uses the macro } int main() { // uses the macro printf("%f\n", sin(3.14)); // uses the function double (*x)(double) = &sin; // uses the function printf("%f\n", (sin)(3.14)); }
650,708
650,723
Is it valid to pass a pointer to a stack variable to realloc()?
int main() { char myString = NULL; realloc(&myString, 5); strncpy((char *)&myString, "test", 5); } Seems to work fine but I'm still slightly confused about stack vs heap. Is this allowed? If it is allowed, does myString need to be freed manually or will it be released when it goes out of scope? Edit: Thanks for the responses, so i presume this is equally illegal //I want the code to change myString to "tests" char myString[5] = "test"; realloc(&myString, strlen(myString)+2); myString[4] = 's'; myString[5] = '\0';
No, this is completely wrong. realloc should only be used to reallocate memory allocated by malloc, what you are doing works only by accident, and will eventually crash horribly char *myString = malloc(x); myString = realloc(myString,y); free(myString) You are better off using new and delete, and even better off using std::string, however.
650,770
650,783
C++: Is it possible to share a pointer through forked processes?
I have a count variable that should get counted up by a few processes I forked and used/read by the mother process. I tried to create a pointer in my main() function of the mother process and count that pointer up in the forked children. That does not work! Every child seems to have it's own copy even though the address is the same in every process. What is the best way to do that?
Each child gets its own copy of the parent processes memory (at least as soon as it trys to modify anything). If you need to share betweeen processes you need to look at shared memory or some similar IPC mechanism. BTW, why are you making this a community wiki - you may be limiting responses by doing so.
650,889
650,901
Is there a way to prevent the hide operation of a toolbar?
In Qt, if I right-click on a toolbar the menu will be shown that allows me to hide the toolbar. I need to disable this functionality because I don't want the toolbar to possible to hide. Is there a way to do this?
Inherit QToolbar and reimplement contextMenuEvent().
650,931
650,977
C++ MI static template - static method disapears at join
#include <iostream> using namespace std; /* TA <-- defines static function / \ | B <-- subclass TA, inherits it so B::StaticFunc can be used. \ / C <-- want to inherit static func from A, subclass B privately */ template <class T> class TA { public: // return ptr to new instance of class T static T * instance() { static T inst; return &inst; } }; class B : public TA<B> { public: void Func() { cout << "B" << endl; } }; /* HERE: class C : public TA<C> */ class C : public TA<C>, private B { public: void Func() { cout << "C" << endl; } }; int main() { C test(); B::instance()->Func(); C::instance()->Func(); /* Expected output: B C Actual error: error: `instance' is not a member of `C'| If i do not subclass B with C, then it compiles. However, I need C to provide some other functionality and but a subclassable Singleton */ return 0; }
I get a different, more reasonable error (with g++ 4.3.3): tst.cpp: In function ‘int main()’: tst.cpp:49: error: reference to ‘instance’ is ambiguous tst.cpp:22: error: candidates are: static T* TA<T>::instance() [with T = B] tst.cpp:22: error: static T* TA<T>::instance() [with T = C] This can be fixed by explicitly specifying which version of instance should be used in C: class C : public TA<C>, private B { public: using TA<C>::instance; void Func() { cout << "C" << endl; } };
651,012
651,109
returning a set of keys in the map matching the criteria
First I will give a specific case, and the I would like to see if it can be applied to a general problem. Say I have map. And I want to get all the keys meeting a certain criteria. For example all keys that contain "COL". My naive implementation will be template<typename T> void Filter (map<string, T> & m, std:set<string> & result, const std::string& condition) { for(map<string,string> iter=m.begin();iter!m.end();iter++) { std::string key=iter->first; size_t found=key.find(condition); if (found!=string::npos) result.insert(key); } } what is the good way to implement this? Also, what is a good way to implement general problem when I want to filter map using algos?
I think your solution is rather good: it is clear, and except if you can "guess" hash values based on the condition, I don't think you could be much more performant. However, you could change your function to make it more generic: template<typename TKey, typename TValue, typename Predicate> void filter (const map<TKey, TValue> & m, set<TKey> & result, Predicate & p) { typename map<TKey,TValue>::const_iterator it = m.begin(); typename map<TKey,TValue>::const_iterator end = m.end(); for( ; it != end ; ++it) { TKey key = it->first; if (p(key)) result.insert(key); } } Your example can then be writen using a functor as predicate: struct Contains { Contains(const string & substr) : substr_(substr) {} bool operator()(const string & s) { return s.find(substr_) != string::npos; } string substr_; }; The call to filter will then look like this: map<string, Obj> m; // Insert in m set<string> res; filter(m, res, Contains("stringToFind"));
651,060
653,332
Returning an object as a property in ATL
I am creating a COM object using Visual Studio 2008 and ATL. Adding simple properties and methods is easy enough but now I want to do something more complicated. I want to give access to a C++ object via a property of my COM object, so I can do something like: // Pseudo-code var obj = CreateObject("progid"); obj.aProperty.anotherProperty = someValue; So, aProperty returns a reference to another object which exposes a property called anotherProperty. I'm guessing that I need to add another simple ATL object to my project for the second object (call it IClass2), and have something like the following in the IDL: [propget, id(1)] HRESULT aProperty([out, retval] IClass2** ppValue); Am I on the right track here? Does anyone know of a good tutorial for this sort of thing?
I just came across this article: HOWTO: Implement static object hierarchies in ATL This looks very similar to what I am trying to achieve.
651,154
651,188
why does throw "nothing" causes program termination?
const int MIN_NUMBER = 4; class Temp { public: Temp(int x) : X(x) { } bool getX() const { try { if( X < MIN_NUMBER) { //By mistake throwing any specific exception was missed out //Program terminated here throw ; } } catch (bool bTemp) { cout<<"catch(bool) exception"; } catch(...) { cout<<"catch... exception"; } return X; } private: int X; }; int main(int argc, char* argv[]) { Temp *pTemp = NULL; try { pTemp = new Temp(3); int nX = pTemp->getX(); delete pTemp; } catch(...) { cout<<"cought exception"; } cout<<"success"; return 0; } In above code, throw false was intended in getX() method but due to a human error(!) false was missed out. The innocent looking code crashed the application. My question is why does program gets terminated when we throw "nothing”? I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?
This is expected behaviour. From the C++ standard: If no exception is presently being handled, executing a throw-expression with no operand calls terminate()(15.5.1). As to why the compiler can't diagnose this, it would take some pretty sophisticated flow analysis to do so and I guess the compiler writers would not judge it as cost-effective. C++ (and other languages) are full of possible errors that could in theory be caught by the compiler but in practice are not.
651,158
652,714
CBlobCache usage - ATL Server Library
Someone may have an example of use for CBlobCache?
BlobCache documentation and samples are on MSDN.
651,198
652,151
can you create a lib or dll in VS 2005 and link with VS 2008
I am using visual studio 2008 SP1. And I am creating a desktop application using MFC. I have a library I want to link with my application. However, the library was written in WIN32 visual studio 2005. I am been having a trouble linking: fatal error LNK1104: cannot open file 'AgentLib.lib' I am wondering if it is because I am using MFC 2008 and the library was written and compiled with 2005? Many thanks for any advice,
Make sure you have added the path where your lib files are under project settings in Linker>General>Additional Library Directories
651,497
651,502
How to do std::string indexof in C++ that returns index of matching string?
I'm looking for a string indexof function from the std namespace that returns an integer of a matching string similar to the java function of the same name. Something like: std::string word = "bob"; int matchIndex = getAString().indexOf( word ); where getAString() is defined like this: std::string getAString() { ... }
Try the find function. Here is the example from the article I linked: string str1( "Alpha Beta Gamma Delta" ); string::size_type loc = str1.find( "Omega", 0 ); if( loc != string::npos ) { cout << "Found Omega at " << loc << endl; } else { cout << "Didn't find Omega" << endl; }
651,834
651,856
Deterministic Random Number Streams in C++ STL
I want to supply a number, and then receive a set of random numbers. However, I want those numbers to be the same regardless of which computer I run it on (assuming I supply the same seed). Basically my question is: in C++, if I make use of rand(), but supply srand() with a user-defined seed rather than the current time, will I be able to generate the same random number stream on any computer?
srand() & rand() are not part of the STL. They're actually part of the C runtime. Yes, they will produce the same results as long as it's the same implementation of srand()/rand(). Depending on your needs, you might want to consider using Boost.Random. It provides several high-quality random number generators.
652,155
652,249
invalid use of incomplete type
I'm trying to use a typedef from a subclass in my project, I've isolated my problem in the example below. Does anyone know where I'm going wrong? template<typename Subclass> class A { public: //Why doesn't it like this? void action(typename Subclass::mytype var) { (static_cast<Subclass*>(this))->do_action(var); } }; class B : public A<B> { public: typedef int mytype; B() {} void do_action(mytype var) { // Do stuff } }; int main(int argc, char** argv) { B myInstance; return 0; } This is the output I get: sean@SEAN-PC:~/Documents/LucadeStudios/experiments$ g++ -o test test.cpp test.cpp: In instantiation of ‘A<B>’: test.cpp:10: instantiated from here test.cpp:5: error: invalid use of incomplete type ‘class B’ test.cpp:10: error: forward declaration of ‘class B’
The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your case. So what happens is that A<B> is instantiated at class B : public A<B> at which point B is not a complete type yet (it is after the closing brace of the class definition). However, A<B>::action's declaration requires B to be complete, because it is crawling in the scope of it: Subclass::mytype What you need to do is delaying the instantiation to some point at which B is complete. One way of doing this is to modify the declaration of action to make it a member template. template<typename T> void action(T var) { (static_cast<Subclass*>(this))->do_action(var); } It is still type-safe because if var is not of the right type, passing var to do_action will fail.