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
3,227,339
3,227,365
What are alternatives to the GetShortPathName function?
I'm looking for a function which can return the 'short' (8.3 notation) path for a given 'long' path. However, the GetShortPathName function (which seemed like a perfect fit) doesn't work for me since it requires thata file with the given long path exists already. What other options do I have for computing the 8.3 path for a given long path?
If the file does not exist, it does not have an 8.3 name. The 8.3 name is created when the file is created. You can of course get the 8.3 pathname for the directory it's in using GetShortPathName on the directory itself, if you need that. Regardless, this is 2010. It's really backwards to be using 8.3 names for anything.
3,227,417
3,227,480
Clarification regarding C++ Exception Handling / Throwing
Consider the following code: try { int *i = NULL; i[100] = 20; catch (...) { std::cout << "Exception Caught"; } When running this code, it crashes (obviously, accessing a NULL pointer). Although, in Debug mode, Visual Studio states about an Uncaught exception, regarding write access violation.. also understandable. I expected an exception to be caught here, but none is. My conclusion is that no exception is being thrown. So why is VS alerting about an uncaught exception ? This question all started when I wanted to protect myself from code by another programmer, and wanted to wrap the calls to his functions with try-catch, assuming that he might be doing some access violations. But if I can only catch exceptions that are expicitily thrown, I'm pretty screwed. The only other explanation I may have is that this is because of some kind of Project or compiler configuration. I ran this in a new C++ Console Application is VS2005. Thanks
Access violation is not C++ exception and cannot be caught by catch operator. Unhandled exception message in the Output window doesn't mean that this is C++ exception. First-chance and unhandled exception messages are generated both for C++ exceptions and any other exceptions like access violation. Non-C++ exceptions can be caught by __try - __except block.
3,227,434
3,227,484
Problem with passing by reference
Can I overload a function which takes either a reference or variable name? For example when I try to do this: void function(double a); void function(double &a); I would like the caller of this function to be able to do: double a = 2.5; function(a); // should call function(double &a) function(2.3); // should call function(double a) I would like to write pass-by-reference functions for better memory use and possible manipulation of the variable outside of scope, but without having to create a new variable just so I can call the function. Is this possible? Cheers
I think you're missing the point here. What you really should have is JUST this: void function(const double &a); Note the "const". With that, you should always get pass-by-reference. If you have non-const pass by reference, then the compiler will correctly assume that you wish to modify the passed object - which of course is conceptually incompatible with the pass-by-value variant. With const references, the compiler will happily create the temporary object for you behind your back. The non-const version doesn't work for you, because the compiler can only create these temporaries as "const" objects.
3,227,608
3,229,532
How easy is Lua with Qt, compared to QtScript?
I'm just starting C++ development using Qt. However, I'm also interested in using Lua to script my app, given various articles stating its development speed (ease) for writing the workflow/ui/glue of an application. However, out of the box Qt doesn't support it, instead it includes QtScript. My question is basically should I attempt to use Lua with Qt to develop a commercial app, or stick with QtScript available in the SDK? Primarily a development speed vs. stability question I guess.
I've encountered the same dilemma. I much prefer Lua to ECMAScript for these sorts of tasks. However, as easy as it is to write Lua bindings, the level of integration provided by QtScript yields a lot of capability out of the box. This includes bindings to built-in QObject-derived classes as well as your own classes that inherit from QObject and/or QScriptClass. So, if you only want to script or configure your own classes independent from Qt functionality, then I'd go with Lua. However, if you primarily want to interact with QObject-based types, then QtScript will greatly decrease your initial development time. The best of both worlds would be the option to parse Lua scripts with an alternate QScriptEngine implementation. I've been meaning to look into how difficult that would be to integrate for some time... UPDATE: QtLua is still actively maintained and might solve your problem directly.
3,228,083
3,228,103
Which STL container for ordered data with key-based access?
Let's say I have a collection of Person objects, each of which looks like this: class Person { string Name; string UniqueID; } Now, the objects must be stored in a container which allows me to order them so that I can given item X easily locate item X+1 and X-1. However, I also need fast access based on the UniqueID, as the collection will be large and a linear search won't cut it. My current 'solution' is to use a std::list in conjunction with a std::map. The list holds the Persons (for ordered access) and the map is used to map UniqueID to a reference to the list item. Updating the 'container' typically involves updating both map and list. It works, but I feel there should be a smarter way of doing it, maybe boost:bimap. Suggestions? EDIT: There's some confusion about my requirement for "ordering". To explain, the objects are streamed in sequentially from a file, and the 'order' of items in the container should match the file order. The order is unrelated to the IDs.
boost:bimap is the most obvious choice. bimap is based on boost::multi_index, but bimap has simplified syntax. Personally I will prefer boost::multi_index over boost::bimap because it will allow to easily add more indices to the Person structure in the future.
3,228,288
3,419,825
Howto resolve compiler specific runtime initialization functions for a library from the main application
What is the best practice when doing a mixed language library where the library language requires a runtime initialization? I have a problem where I'd like to create a certain library in Fortran which is to used from C++. I'd want to preserve platform independence and compiler independence if possible. Now, the two compilers I have played with, G95 and GFortran both require that the main application calls certain compiler-specific initialization routines to properly set up the runtime before using the library. These functions have different names and signatures depending on the compiler (for G95 the function is void g95_runtime_start(int argc, char *argv[]) ) I'm using CMake to manage the project and the library subproject is a static library. Do I somehow in my cmake file for the main application have to dig out which fortran compiler is used for the library subproject and then let CMake create a define in the main project so that I can conditionally compile the main app with either init routine? It feels very awkward. Is there a better way?
There is support for the name mangling and alternative mains (AC_FC_MAIN) in autoconf. I know there were some discussions on this in the cmake group also, so it might be available in the FortranCinterface module. However I could not find any docs on that. I prefer to work with autotools over cmake because these type of issues are already solved and well documented.
3,228,698
3,228,721
Define not evaluating POD?
I was going over the C++ FAQ Lite online. I was browsing inlines again since I haven't found a use for them and wanted to know how the stopped the circular dependency as showed in this answer. I first tried to do the, "Why inlines are better than defines." example with the following code: #define unsafe(i) \ ( (i) >= 0 ? (i) : -(i) ) inline int safe(int i) { return i >= 0 ? i : -(i); } int f(); int main(void) { int x(5); int ans; ans = unsafe(x++); cout << ans << endl; ans = unsafe(++x); cout << ans << endl; ans = safe(x++); cout << ans << endl; ans = safe(++x); cout << ans << endl; std::cin.get(); return 0; } EDIT: Great. Got the typo out of the way. Not that I'm bitter that I don't find such errors or anything. The output is now 6, 9, 9, 11. However, even with pre-incrementation, shouldn't the first value result in 7? If the macro is being called twice, then doesn't it go like this: unsafe(x) // pre-incrementation doesn't modify the value when called. unsafe(++x) // for all intents and purposes, the incrementation happens before the second call, so the ++x. This is for the first ans = unsafe(x++) if it's being called twice. By the time we reach the second ans = unsafe(++x), shouldn't the x have been incremented twice? Once by the double call and once when the first double call was finished?
Instead of: #define unsafe(i) \ ( (i) >= 0 = (i) : -(i) ) I think you want: #define unsafe(i) \ ( (i) >= 0 ? (i) : -(i) ) In response to your edit: After the first call to unsafe(x++), x is 7, even though the ans is 6. This is because you have the statement: ans = ( (x++) >= 0 ? (x++) : -(x++) ) ans is assigned to the middle x++ after the left-most x++ is evaluated. As a result, ans == 6 but x == 7. The difference with unsafe(++x) is that ans is assigned to ++x, meaning the result is ans == x == 9.
3,228,906
3,228,933
Does std::string::assign takes "ownership" of the string?
I have some gaps in the understanding of string::assign method. Consider the following code: char* c = new char[38]; strcpy(c, "All your base are belong to us!"); std::string s; s.assign(c, 38); Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer; i.e. doesn't allocate new memory and uses directly my address. If it copies, then what is the difference between assign and operator=? If it doesn't copy, then does it free the memory or it is my responsibility? Thank you.
Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer; The STL string method assign will copy the character array into the string. If the already allocated buffer inside the string is insufficient it will reallocate the memory internally. The STL string will not take ownership of the original array. If it copies, then what is the difference between assign and operator=? Both ought to act in the same way, but there are a number of overloads to the STL assign method which give you more control over what happens. Take a look at this page for more information. UPDATE: The MSDN has a number of examples of the various assign overloads. If it doesn't copy, then does it free the memory or it is my responsibility? No, the original pointer to the character array is still your responsibility.
3,229,012
3,229,964
Error compiling Visual Studio C++ project - error with cl.exe
I'm running Visual Studio 2005 Pro, and have been getting the following error recently: Error 1 Error result -1 returned from 'C:\Program Files\Microsoft Visual Studio 8\VC\bin\cl.exe'. Reading some of the other posts around here, I've learned that cl.exe is native to VS 2008. I do have an install of 2008 Express (but C# only), and recently I uninstalled VS 2010 Express. Could there be some sort of leftover compatibility issue going on here for me? edit Ok, let's go with it isn't a compatibility issue. Any thoughts on how to fix the error?
It turns out that the error is not with Visual Studio, but with the test suite that I'm ultimately working with. It replaces cl.exe and link.exe with its own executables, and moves them to different filenames. Fixing some issues with my test suite made it work again. I didn't realize this until I ran cl.exe from the VS command line...thanks for the suggestions though!
3,229,084
3,229,117
Is it correct/proper to use DialogBox as the main window?
Is it correct-proper as in windows doesn't say it's bad or not recommended. For example like this: int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); UNREFERENCED_PARAMETER(nCmdShow); INT_PTR result = DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAINWINDOWBOX), nullptr, MainWindow); return static_cast<int>( result ); }
Using a Dialog Box as the main window is actually supported as one of the default configurations by MFC, so yes, that's fine (according to Microsoft). For what it's worth, virtually every Windows app I've written in years used a dialog box as the main window, but that's because I don't write office-type applications.
3,229,333
3,229,357
Finding arguments that go with methods in C++ dll's
Ok, so I can use dumpbin.exe /exports library.dll to find all methods in the dll. ...but how do I find out which arguments to pass into them? Without a header file of course.
For the usual C-style exports (e.g., Windows API DLLs): You can't. This information is not stored in the DLL and is inevitably lost after compilation (unless you have the headers or debuging symbols). C++ exports, on the other hand, store their signature as part of the mangled function name and you can view them using Dependency Walker or similar tools, or demangle them manually using the UNDNAME tool or DUMPBIN's /SYMBOLS option.
3,229,391
3,279,236
SDL + SDL_ttf: Transparent blended text?
I want to render an anti-aliased string on an SDL_Surface with a given alpha channel. I figured out it is possible to render: an anti-aliased string with the Blended variant of the string render method (ie: TTR_RenderText_Blended). But then I can't make it transparent. An anti-aliased string with the Shaded method. But then there is a solid background. The background and the drawn string can be made transparent, but then the solid background is still there. Passing it a transparent background color is also not possible. an non-anti-aliased string, which I can make transparent like I want with the Solid variant. But it is not anti-aliased. Thanks
Why not use bitmapped fonts? You could build a png image with alpha channel. I think that SDL_ttf works with the same system, it builds an image an internally uses bitmapped fonts.
3,229,459
3,229,582
Algorithm to cover maximal number of points with one circle of given radius
Let's imagine we have a plane with some points on it. We also have a circle of given radius. I need an algorithm that determines such position of the circle that it covers maximal possible number of points. Of course, there are many such positions, so the algorithm should return one of them. Precision is not important and the algorithm may do small mistakes. Here is an example picture: Input:   int n (n<=50) – number of points;   float x[n] and float y[n] – arrays with points' X and Y coordinates;   float r – radius of the circle. Output:   float cx and float cy – coordinates of the circle's center Lightning speed of the algorithm is not required, but it shouldn't be too slow (because I know a few slow solutions for this situation). C++ code is preferred, but not obligatory.
Edited to better wording, as suggested : Basic observations : I assume the radius is one, since it doesn't change anything. given any two points, there exists at most two unit circles on which they lie. given a solution circle to your problem, you can move it until it contains two points of your set while keeping the same number of points of your set inside it. The algorithm is then: For each pair of points, if their distance is < 2, compute the two unit circles C1 and C2 that pass through them. Compute the number of points of your set inside C1 and C2 Take the max.
3,229,660
3,229,686
How to delete object created in another thread in C++
There is a long-time request and is called from the "main" (UI) thread. It is planned to move it's call into a separate thread. The problem is that some objects are created in this thread on the heap (main thread will have to work with these pointers). Questions: Is it allowed to delete 'another-thread' objects in the main thread? Is it a good idea to delete object in "another" thread.
Yes. Depending on situation, this is not bad and not good, just do what you need according to your algorithm. Deleting objects created in another thread may be dangerous only if object destructor works with a thread local storage. This must be mentioned in the class documentation.
3,229,807
3,229,997
C++ inheritance/template question
I have two classes, point and pixel: class point { public: point(int x, int y) : x(x), y(y) { }; private: int x, y; } template <class T> class pixel : public point { public: pixel(int x, int y, T val) : point(x, y), val(val) { }; private: T val; } Now here's my problem. I want to make a container class (let's call it coll) that has a private vector of points or pixels. If an instance of coll contains pixels, I want it to have a method toArray(), which converts its vector of pixels to an array of T representing the contents of the vector. I was going to do this with inheritance: ie, I could make a base class coll that contains a vector of points and a derived class that contains the extra method, but then I seem to run into problems since pixel is a class template. Does anyone have suggestions? Could I do this somehow by making coll a class template?
Question: Do you mean for the private vector to contain both Points and Pixels at the same time, or just one or the other? Question: If just one or the other, are you meaning to mix Pixels with different template parameters in the same private vector? Assuming that it is just Point or Pixel in the private vector, and that the Pixels in the private vector all have the same template parameter, you could do something like this: template < class T > class CollectionBase { //common interface here protected: std::vector<T> coll_vec; }; class PointCollection : public CollectionBase<Point> { public: ... }; template< class T> PixelCollection : public CollectionBase<Pixel<T> > { public: Pixel<T>* toArray(); ... };
3,229,883
3,229,904
Static member initialization in a class template
I'd like to do this: template <typename T> struct S { ... static double something_relevant = 1.5; }; but I can't since something_relevant is not of integral type. It doesn't depend on T, but existing code depends on it being a static member of S. Since S is template, I cannot put the definition inside a compiled file. How do I solve this problem ?
Just define it in the header: template <typename T> struct S { static double something_relevant; }; template <typename T> double S<T>::something_relevant = 1.5; Since it is part of a template, as with all templates the compiler will make sure it's only defined once.
3,230,042
3,230,108
Where does the word trait comes from?
I understand that C++ Traits are compile time properties that can be used to take some compile time choices for templates, but where does they come from ? Can anyone point out some basic background material about the concepts behind traits ? Where does the word traits come from ? EDIT: I guess I should refine the question. I know of "character trait" (or "trait de caractère" in French for Philipp), but who thought about applying it to software ingeeneering to describe some kind of properties, and does it have the specific meaning I attach to it "compile time property" ?
C++ Type traits by John Maddock and Steve Cleary http://www.boost.org/doc/libs/1_31_0/libs/type_traits/c++_type_traits.htm Traits: a new and useful template technique by Nathan C. Myers: http://www.cantrip.org/traits.html very helpful! Matthew
3,230,319
3,322,458
How to read a user's input from the console into a Unicode string?
A C++ beginner's question. Here is what I have currently: // From tchar.h #define _T(x) __T(x) ... // From tchar.h #define __T(x) L ## x ... // In MySampleCode.h #ifdef _UNICODE #define tcout wcout #else #define tcout cout #endif ... // In MySampleCode.cpp CAtlString strFileName; if (bIsInteractiveMode) { char* cFileName = new char[513]; tcout << endl; tcout << _T("Enter the path to a file that you would like to XYZ(purpose obfuscated) ") << endl; tcout << _T(">>> "); cin.getline(cFileName, 512); strFileName = cXmlFileName; } // Demonstrates how CAtlString can be printed using `tcout`. tcout << _T("File named '") << strFileName.GetString() << _T("' does not exist.") << endl; This happens to "work" in the US, but I have no idea what will happen if ... say a French user is running this app and starts to enter weird characters such as Çanemeplaîtpas.xml on command line. I am looking for a clean way to populate a string of the CAtlString type. The maximum length of the input can always be set long enough, but ideally I would like to limit the unicode, and non-unicode entries to the same number of characters. Hopefully doing so is reasonably easy and elegant.
Shouldn't you be using wcin stream if you expect unicode input? #include <iostream> #include <string> #include <locale> int main() { using namespace std; std::locale::global(locale("en_US.utf8")); std::wstring s; std::wcin >> s; std::wcout << s; }
3,230,354
3,230,464
Finding a Subset of Points by Relative Distances
I'm writing a game in which the player may manipulate a great many objects at one time. I would like the player to be able to select objects according to the distances between them. Given the locations of all objects, a starting object, and a distance threshold, what is the fastest way to find the subset containing the starting object for which the distance between any two objects does not exceed the threshold? Heuristic solutions are perfectly acceptable.
This library seems to do the trick: "ANN is a library written in the C++ programming language to support both exact and approximate nearest neighbor searching in spaces of various dimensions. [...] In the nearest neighbor problem a set P of data points in d-dimensional space is given. These points are preprocessed into a data structure, so that given any query point q, the nearest (or generally k nearest) points of P to q can be reported efficiently."
3,230,368
3,230,443
boost shared_ptr and 'this'
I have two classes with a parent-child relationship (customer&order directory&file etc) I have typedef boost::shared_ptr<Parent> ParentPtr and in parent class a method to make a child I need child instances to have pointers to their parent. class Child { .... ParentPtr m_parent; .... } I want it to be a shared_ptr so that the parent doesn't disappear while there are existing children. I also have other people holding ParentPtrs to the parent (the factory method for Parents returns a ParentPtr) Question: how can give the child a ParentPtr attempt (1) . In Parent::ChildFactory child->m_parent.reset(this); this results in very bad things. There are now 2 ParentPtr 'chains' pointing at the parent; result is premature death of Parent attempt (2). Parent has ParentPtr m_me; which is copied from the return value of the Parent factory. So I can do child->m_parent = m_me; But now Parent never dies because it holds a reference to itself
I'm fairly sure that enable_shared_from_this solves your problem: http://live.boost.org/doc/libs/1_43_0/libs/smart_ptr/enable_shared_from_this.html If you derived your class from a specialization of boost::enable_shared_from_this then you can use shared_from_this() in a member function to obtain the shared pointer that owns this (assuming that there is one). E.g. class Parent : public boost::enable_shared_from_this<Parent> { void MakeParentOf(Child& c) { c.m_parent = shared_from_this(); } };
3,230,420
3,230,454
How to know if a pointer points to the heap or the stack?
Example: bool isHeapPtr(void* ptr) { //... } int iStack = 35; int *ptrStack = &iStack; bool isHeapPointer1 = isHeapPtr(ptrStack); // Should be false bool isHeapPointer2 = isHeapPtr(new int(5)); // Should be true /* I know... it is a memory leak */ Why, I want to know this: If I have in a class a member-pointer and I don't know if the pointing object is new-allocated. Then I should use such a utility to know if I have to delete the pointer. But: My design isn't made yet. So, I will program it that way I always have to delete it. I'm going to avoid rubbish programming
There is no way of doing this - and if you need to do it, there is something wrong with your design. There is a discussion of why you can't do this in More Effective C++.
3,230,681
3,231,028
Read Anonymous Pipes More than Once while Keeping Connection Open (WinAPI)
So I keep bouncing between named and anonymous pipes and here is my issue. I tried named pipes and they just didn't seem to work properly for what I wanted, so I'm back to anonymous pipes. However, the anonymous pipe needs to read input from a pipe (to a program that I did not create) and continuously read it as more information is available to the pipe. Here is the relevant code which I currently have: void Arc_Redirect::createProcesses() { TCHAR programName[]=TEXT("program.exe"); PROCESS_INFORMATION pi; STARTUPINFO si; SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; if(!CreatePipe(&outStd[0].hOutRead,&outStd[0].hOutWrite,&sa,0) || !CreatePipe(&outStd[0].hInRead,&outStd[0].hInWrite,&sa,0)) throw "Error: Could not CreatePipe();!"; if(!SetHandleInformation(outStd[0].hOutRead,HANDLE_FLAG_INHERIT,0) || !SetHandleInformation(outStd[0].hInWrite,HANDLE_FLAG_INHERIT,0)) throw "Error: Could not SetHandleInformation();"; // Set stuff up ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.hStdError = outStd[0].hOutWrite; si.hStdOutput = outStd[0].hOutWrite; si.hStdInput = outStd[0].hInRead; si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES; outStd[0].o1.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(!CreateProcess(programName,NULL,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi)) throw "Error: Could not start Program!"; // Cleanup the useless handles if(!CloseHandle(pi.hThread) || !CloseHandle(pi.hProcess)) throw "Error: Could not CloseHandle();"; } And here is how I am reading the pipe: void Arc_Redirect::readPipe() { CHAR chBuf[BUFSIZE]; DWORD dwRead; ReadFile(outStd[0].hOutRead,chBuf,sizeof(chBuf),&dwRead,&outStd[0].o1); chBuf[dwRead] = '\0'; SetDlgItemText(global,IDO_WORLDOUT,chBuf); ResetEvent(outStd[0].o1.hEvent); } BUFSIZE is defined at 0x1000 and outStd is defined as PIPE_HANDLES (struct below) typedef struct { HANDLE hOutRead; HANDLE hOutWrite; HANDLE hInRead; HANDLE hInWrite; OVERLAPPED o1; TCHAR chReq[BUFSIZE]; TCHAR chReply[BUFSIZE]; DWORD dwRead; DWORD dwWritten; DWORD dwState; DWORD cbRet; BOOL pendingIO; } PIPE_HANDLES, *LPSTDPIPE; Now, I can properly call readPipe(); once and it does exactly what I want. However, if I try to call it again, it fails. Any ideas on how I can fix this issue? Like I said, I need to keep the connection open and read incrementally. For sake of argument, say I need to read every 5 secs; the program I am reading from will have different output every 5 secs that needs to be read. Any help? Regards, Dennis M.
It is impossible to guess why it fails if you don't find out why. ReadFile returns FALSE when it fails. You should then call GetLastError() to get a diagnostic. Never ignore Windows API return values. At the very least assert them.
3,230,995
3,231,009
Is this the correct syntax for passing a file pointer by reference?
Is this the correct syntax for passing a file pointer by reference? Function call: printNew(&fpt); printNew(FILE **fpt) { //change to fpt in here kept after function exits? }
No. The correct syntax is void printNew(FILE *&fpt) { //change to fpt in here kept after function exits? } Your code will only change the local pointer to a FILE pointer. Only changes to *fpt are seen by the caller in your code. If you change it to the above, things are passed by reference and changes are promoted like intended. The corresponding argument is passed as usual printNew(fpt);
3,231,128
3,231,692
Alternative to GLUTesselator?
I was wondering if there was a library or another way to produce multi contour polygons in OpenGL. I did code profiling and the GLUTesselator is killing my loop. Thanks Bounty +50 for a library with a GPL-compatible license, and ideally 3D (second best would be 2.5D like GLUtesselator itself.)
There's always GPC. EDIT: Some others: Flipcode mystery triangulator. Slower than GPC in my extremely limited, probably wrong tests. poly2tri is BSD-licensed. EDIT2: Earcut.hpp is now a thing.
3,231,599
3,231,778
Intercepting a WM_PAINT message and acting upon this
I'm trying to intercept/hook the WM_PAINT message of the desktop in C++. I'm currently drawing with the desktop handle, my only problem is that I'm not in sync so it might flicker. What I basically would like is a statement where I can check on the WM_PAINT of UINT message. When this is the case, I want to do something else. I'm going to ask it the lazy way, does anyone have this laying around in a small piece of code? Obtaining the desktop handle is done with GetDesktopWindow(); from this I want too check for WM_PAINT.
I'd check SetWindowHookEx (see: SetWindowsHookEx in C# )
3,231,611
3,231,779
Visual C++ Warning C4800, why does it only trigger on return statements?
I have just installed the Windows SDK v7.1 (MSVC 10.0) and running my code through (almost) full warning level (W3, default for qmake's CONFIG += warn_on) and am surprised about warning C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning) In the following code, stream is an std::istream and token is a std::string. // in some function returning bool return (stream >> token) // triggers warning c4800: // '(void *)': forcing value to bool 'true' or 'false' (performance warning)` // somewhere else if( stream >> token ) // does not trigger warning c4800 What is going on here? I don't even get why the warning is triggered in the first place. I thought the first bit of code already returned a bool anyways. I understand this is nitpicking and the warning shouldn't even exist, but it's the only one in my code between MSVC's /W3 and gcc's -Wall -pedantic, so I'd like to know :) SMALL UPDATE: I understand that the warning is designed to let you know you're assuming int->bool conversion, but 1) why would you even still use bool (==typedef int mostly) and 2) why would an if(2) not convert 2 to true or false, I thought that was the whole idea of a predicate, being true or false.
What is going on here? I don't even get why the warning is triggered in the first place. I thought the first bit of code already returned a bool anyways. Streams have an implicit conversion operator that returns a void*. (That's a version of the safe bool idiom. It's done this way because there is less contexts in which void* compiles than bool, so there's less contexts in which the implicit conversion could kick in unwanted.)[1] Streams' operator>>() returns a reference to its left operand - the stream. That's so you can chain input operations: strm >> value1 >> value2 is executed as ((strm >> value1) >> value2). Now, when you say if( strm >> value ), strm >> value is executed and a stream returned. In order to put that into an if statement, the implicit conversion into void* is performed, and that pointer is then checked for being NULL or not. That's no different from if(ptr), the if statement implicit converts its condition to bool, but compilers would never warn about that, because the condition not being a bool is so common. With the return, this is different. If you want to return a certain type, usually the expression you return should be of that type. VC's warning is quite annoying and for me in 99 out of 100 times it was superfluous. But the remaining 1% (never a performance concern, BTW; I think that is silly about the warning) made me glad the warning is there. The workaround for this warning is to return 0 != <expression> where <expression> is whatever you think should be considered a boolean value. [1] ISTR Stroustrup writing somewhere that an operator bool() would silently compile if you messed up the operators: ostrm >> 5; (note the >> instead of <<) would compile fine, but silently do the wrong thing. (It converts the boolean to an integer and right-shifts that 5 times, then discard the value.)
3,231,707
3,231,808
A Question About Linking/Loading and A Simulator
I have designed a MIPS I simulator using Verilator which allows me to wrap verilog code into c++. I am attempting to run a c++ program on my processor but I've reached some problems. My goal is to: write a test program in c++ compile this program using a cross compiler g++ (mips-linux) take generated ELF file and disassemble it using objdump store the entire binary object dump in a text file open text file in my simulator run some text manipulating functions to isolate the HEX dump portion of the objdump load entire elf hex dump into my processor's memory (a c++ memory map containing elements keyed by their address in memory as defined by the ELF file.) run the program by setting the program counter and letting it go until exit syscall of program. The problem would be steps 7 and 8. I have a very rudimentary understanding of the ELF file format. As far as I can tell (readelf can be used to output a program starting point) the program ounter should be set initially at the address of the beginning of the .text section. Unfortunately doing this does not result in a proper program run on my processor. I have verified proper program execution of my processor by writing assembly programs, loading them into MIPS assembly simulators, and verifying, instruction by instruction, that the register file and generated addressing matches. What I don't understand is why I can't get even a "helloworld" program to run by writing in c++, compiling, and loading into my "memory"? I'm not particularly knowledgeable in this field. I could really use some help figuring this out. My understanding is that .text and .data contain everything needed for my program to run. This is obviously not the case because as I traverse the .text section, my program does not execute correctly. Is there something else I need to do with the ELF file before loading it into memory?
I have written a full MIPS I simulator that can load ELF binaries. You can get the source code here, maybe you'll get answers to your questions. There are also some demo programs included. The key point is to get the compiler to generate a freestanding executable that does not use any run-time library, not even the gcc's support library.
3,231,739
3,231,895
Problem while building a .dll (Visual C++)
I am trying to build a .dll in order to link it to one of my projects. But the build always fails : I got these messages in the output and I don't know what it means. It seems that something is missing, but I couldn't find what. I am trying to link a Mesher called Netgen http://www.hpfem.jku.at/netgen/ 1>adfront2.obj : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification 1> Creating library D:\Documents\Visual Studio 2008\Projects\converter/lib\nglib.lib and object D:\Documents\Visual Studio 2008\Projects\converter/lib\nglib.exp 1>Embedding manifest... 1>Performing Post-Build Event... 1>Environment variable NETGENDIR not found.... using default location!!! 1>POSTBUILD Script for nglib ........ 1>Installing required files into XXX\Netgen\windows....\nglib-instNoOCC_Win32 .... 1>File not found - nglib.dll 1>0 File(s) copied 1>POSTBUILD Script for nglib FAILED..... Error copying the nglib DLL into install folder!!! 1>Project : error PRJ0002 : Error result 1 returned from 'C:\Windows\SysWow64\cmd.exe'. 1>Build log was saved at "file://D:\Documents\Visual Studio 2008\Projects\converter\BuildLog_nglib.htm" 1>nglib - 1 error(s), 49 warning(s) I hope I am clear enough and thank you by advance for your help.
seems this NetGen lib's project wants to run a post-build event in which it tries to copy the main output (the nglib.dll) to the directory NETGENDIR (which is supposed to be an environment variable). This fails beccuse the dll isn't found. Either disable the post build event, or check with the NetGen lib's creator what they expect here, there seems to be a mismatch between the project's output dir and the postbuild event. Would also be nice to see the postbuild event from the vcproj file, maybe you can post it?
3,231,924
3,232,005
What should I code to get into the depths of advanced C++?
I'm looking for project suggestions that would force me to "get my hands dirty" with advanced C++ features. I'm talking about projects that would utilize the full power of the language (STL or even boost (didn't use it much yet)). Why? Because I want to learn, I want to find new challenges. At work, things start to be boring, really. I was used to constantly encountering new things, new ideas and features. This is most of the time not the case of legacy company code, as you can imagine. And still, looking at some questions and answers here that delve into the depths of templates, shared pointers and all that stuff I happen to find myself lost, not knowing the answer or even worse - not even understanding what's going on. That's why I'm looking for something I could code myself, using preferably only C++ (+ boost perhaps) - a command line utility, no graphics please. And I really do not want to join any open source community. Looking at others' code is helpful, I know. But that's what I do at work a lot so... no thanks. The project can be anything, meaningful or meaningless, a useful utility or just something made up that has no real usage. The only requirement is, that it would force me to really test my C++ skills. Or at least it should be very difficult or even impossible to code with basic knowledge of C++ - I'm the kind of person who is never satisfied with code that just works, so I believe this will force me to learn. But bear in mind that I'm a working man and my time is limited, so answers like "code your own OS" really won't help much.
What should i code to get into the depths of advanced C++? Learn more, learn yet more, learn even more. And, no, I'm not joking. Not at all. I started to learn C++ about 15 years ago and I'm still learning new stuff on a regular base. Have a look at The Definitive C++ Book Guide and List and make your pick. I'd recommend Modern C++ Design by Andrei Alexandrescu and C++ Templates The Complete Guide by Vandevoorde & Josuttis. These two alone are enough mind-blowing input to keep one programmer getting new ideas for months, if not years. (Note that reading them in this order has the advantage that Andrei's book is thinner and makes you want to read the other one just to fully grok what he writes. Reading them in reverse order has the advantage that you won't get lost as often in Andrei's book. Whatever you prefer.)
3,232,257
3,232,470
calling GetModuleFileNameEx via psapi.dll is not working, but why?
I am using MinGW which does not have full functionality. eg. It has no wchar_t stream support. I've managed to get around that by writing a mini-set of manipulators (the wcusT() in the code below).. but I find I'm getting stymied again with GetModuleFileNameEx. I have not been able to natively run GetModuleFileNameEx() This function is defined in <psapi.h>, but there seems to be nothing for it to link to. That is my no.1 question: Can/does/is MinGW able to run GetModuleFileNameEx? What do I need to do? Am I missing something simple? As a workaround, I've tried to run it indirectly via a call to its dll (psapi.dll) which is in the Windows system32 folder... but something is wrong. I've got another no-go situation. I'd appreciate any comments on the code below .. thanks int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow) { /// typedef and load a dll function /// =============================== typedef DWORD (__stdcall *foo)(HANDLE, HMODULE, LPTSTR, DWORD); LPTSTR ptcPSAPI_DLL = _T("C:\\WINDOWS\\system32\\psapi.dll"); HMODULE hPSAPI_DLL = LoadLibrary(ptcPSAPI_DLL); if( !hPSAPI_DLL ) { std::cout<<"ERROR: Failed to load "<<wcusT(ptcPSAPI_DLL)<<std::endl; return 1; } foo GetModFnEx=(foo)GetProcAddress(hPSAPI_DLL, #ifdef UNICODE "GetModuleFileNameExW"); #else "GetModuleFileNameExA"); #endif /// call the dll library function /// ============================= HWND hWndNPP = FindWindow(_T("Notepad++"),NULL); // the window calass name TCHAR ytcMFqFn[FILENAME_MAX]; // the buffer for the file name DWORD dwBytes = (GetModFnEx)( hWndNPP, NULL, ytcMFqFn, sizeof(ytcMFqFn) ); DWORD dwError = GetLastError(); std::cout<<wcusT(_T("hWndNPP "))<<"="<<hWndNPP <<"="<<std::endl; std::cout<<wcusT(_T("ytcMFqFn "))<<"="<<wcusT(ytcMFqFn)<<"="<<std::endl; std::cout<<wcusT(_T("dwBytes "))<<"="<<dwBytes <<"="<<std::endl; std::cout<<wcusT(_T("dwError "))<<"="<<dwBytes <<"="<<std::endl; return 0; // Output =============== // SBCS // hWndNPP =0x320606= // ytcMFqFn == // dwBytes =0= // dwError =0= // UNICODE // h W n d N P P =0x320606= // y t c M F q F n =(☻æ|♀ = // d w B y t e s =0= // d w E r r o r =0= // ======================
Your calling GetModuleFileNameEx incorrectly HWND hWndNPP = FindWindow(_T("Notepad++"),NULL); DWORD dwBytes = (GetModFnEx)( hWndNPP // this is ment to be a process handle, not a HWND , NULL, ytcMFqFn, sizeof(ytcMFqFn) ); MSDN doc on GetModuleFileNameEx you might try getting a process handle using one of the following ::GetWindowThreadProcessId(hWnd, &dwProcessID); HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessID); // also in PSAPI - EnumProcesses will return an array of app process ids (BOOL(WINAPI *)(DWORD *,DWORD, DWORD *)) GetProcAddress( psapi, "EnumProcesses" );
3,232,534
3,232,577
Why is my 'count leading zero' program malfunctioning?
Here is code which returns number of leading zeros from Hacker's Delight book: #include <iostream> using namespace std; int nlz(unsigned x) { int n; if (x == 0) return(32); n = 1; if ((x >> 16) == 0) {n = n +16; x = x <<16;} if ((x >> 24) == 0) {n = n + 8; x = x << 8;} if ((x >> 28) == 0) {n = n + 4; x = x << 4;} if ((x >> 30) == 0) {n = n + 2; x = x << 2;} n = n - (x >> 31); return n; } int main(){ int x; cin>>x; cout<<nlz(x)<<endl; return 0; } and when I enter number 8 it return 8 and is it correct maybe it should return 3 yes? 8//1000
It returns the number of leading bits that is zero in an unsigned integer , and it assumes an integer is 32 bits. 8 is 0000 0000 0000 0000 0000 0000 0000 1000 binary, and it should return 28 for that, as there's 28 leading bits zero before the first 1 bit. If you're running this on something where an integer is not 32 bits, it won't work.
3,232,545
3,232,603
C++ basic pointer question
I have some shared pointer shared_ptr<T> pointer1(new T(1));. Now, in some other part of code I have an explicit copy of pointer2 (guess it would be stored in a std::map or some other container). Let's say that copy was done like map.insert(make_pair(key1, pointer1));. I am using that second copy only to precache some data and this means that if the main pointer is already invalid, there is no need to store the second pointer. What should I do in this case? Is there any way to force the memory deallocation for the second pointer if I know that pointer1 became invalid in some other part of my code? Or should I take the ugly way - from time to time check my map for pointers which have ptr.unique() set to true and destruct them? Maybe some alternatives / advices? Edit - plain code sample std::map<int, shared_ptr<int> > map; { shared_ptr<int> pointer1(new int(5)); map.insert(std::make_pair(0, pointer1)); } Is there any way / trick to make map contain <0, shared_ptr[NULL]> instead of <0, shared_ptr[5]> after these operations happen? Thanks
It sounds like this is a task for weak_ptr: http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/weak_ptr.htm Try putting them in your table instead of a shared_ptr.
3,232,582
3,232,905
Question about using string::swap() with temporaries
The following segment demonstrates my issue: (compilation error on GCC) stringstream ss; string s; ss << "Hello"; // This fails: // s.swap(ss.str()); // This works: ss.str().swap(s); My error: constSwap.cc:14: error: no matching function for call to 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >::swap(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' basic_string.tcc:496: note: candidates are: void std::basic_string<_CharT, _Traits, _Alloc>::swap(std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>] While I understand that str() in stringstream returns a temporary, it does not make sense and was not immediately apparent that I should have been calling the swap on the temporary with the local variable as parameter instead of my first instinct. Obviously straight assignment works better, and newer C++ standards have move semantics which is perfect, but these are not available for my implementation. Visual Studio does not give this problem due to it being relaxed about the C++ standard. I kinda already understand the whole const reference to a temporary thing (which I assume is the reason for my compilation errors). My question: Can anyone explain to me if this is the only solution, and perhaps explain to me the how to think about this in future so I can spot and work around similar issues? (If no-one has any great insights I'm at least posting this here for people with similar issues)
After having used the swap-with-temporary idiom enough times, with lines like std::vector<int>().swap(v); // clear and minimize capacity or std::vector<int>(v).swap(v); // shrink to fit this does not seem so out of place. It's normal to call swap as a member function of a temporary object. Of course, it's not so idiomatic to use swap to fill in a default-constructed string instead of using a copy constructor, as already mentioned.
3,232,614
3,232,662
how does an optimizing c++ compiler reuse stack slots of a function?
How does an optimizing c++ compiler determine when a stack slot of a function(part of stack frame of a function) is no longer needed by that function, so it can reuse its memory? . By stack slot I mean a part of stack frame of a function, not necessarily a whole stack frame of a function and an example to clarify the matter is, suppose we have a function that has six integer variables defined in its scope, when it's time to use sixth variable in the function, fifth variable's become useless so compiler can use same memory block for fifth and sixth variables. any information on this subject is appreciated.
The easy part is: When a function exits, all local variables of that function are released. Thus, function exit indicates that the whole stack frame can be freed. That's a no-brainer, though, and you wouldn't have mentioned "optimizing compiler" if that's what you were after. In theory, a compiler can do flow analysis on a function, find out which chunks of memory are used at what time, and perhaps even re-order stack allocation based on the order in which variables become available. Then, if new automatic variables are introduced somewhere in the middle of the function or other scope nested within the function (rather than at its beginning), those recently freed slots could be re-used. In practice, this sounds like a lot of spinning gears, and I suspect that stack is simply allocated whenever variables come in scope and popped off en block by decrementing the stack pointer when the scope finishes. But I admit I'm no expert on this topic. Someone with more authoritative knowledge may come along and correct me.
3,232,669
3,238,215
Is there an alternative to suppressing warnings for unreachable code in the xtree?
When using the std::map with types that use trivial, non-throwing, copy constructors, a compiler warning/error is thrown (warning level 4, release mode) for unreachable code in xtree. This is because the std::map has a try-catch in it that helps maintain the state of the tree in the case of an exception, but the compiler figures out that the catch statement will never be called if the stored elements don't throw. These warnings can be easily suppressed with the following lines at the top of the .cpp file: #pragma warning(push) #pragma warning(disable:4702) #include <xtree> #pragma warning(pop) Is there a way to bypass this warning/error without changing the warning level, building in debug, suppressing the warning, or using a different type in the map? Is there plans to change this in the standard library? Update: Maybe it is compiler specific. I am using vc7. The error is below: c:\program files\microsoft visual studio .net 2003\vc7\include\xtree(1116) : error C2220: warning treated as error - no 'object' file generated c:\program files\microsoft visual studio .net 2003\vc7\include\xtree(1116) : warning C4702: unreachable code Apparently the xtree is used by the std::map.
Unfortunately it looks like xtree is part of the underlying implementation of map in VC7, and as such there isn't much that can be done to mitigate it. It looks like it's a bug in the standard library. Is it a possibility to use a newer compiler? I'm fairly sure there are free downloads of more recent versions of the compiler you could use, and perhaps they've fixed this issue. If that's not an option, probably the best solution is to wrap the include of map into your own private header, complete with a comment and the #pragma+include <xtree> lines you already discovered (in addition to an include of map. This way you hide the workaround from normal use.
3,232,705
3,232,783
Pushing back object, then erasing it at its previous location in std::list
Note that the order can go either way (erase first then push back, just that this way doesn't require creating a local reference to the object). for ( GameObjItr gameObj = m_gameObjects.begin(); gameObj != m_gameObjects.end(); gameObj++ ) { if ( *gameObj && *gameObj != gameObject ) { const sf::FloatRect &otherObj = ( *gameObj )->GetCollisionBox(); if( mainObj.Intersects( otherObj ) ) { m_gameObjects.splice( m_gameObjects.end(), m_gameObjects, gameObj ); return m_gameObjects.back(); } } } return NULL; } The idea is that if the function finds an object colliding with the object passed, it adds that object to the end of the list, erases it from its current position, then returns the object. I don't think iterator invalidation is a problem since I am returning immediately after the erasure? The code causes the program to crash. P.S. cppreference says that erase "deletes" the object, but I assumed that this just removed it from the list. (If this is wrong, how can I remove an element by its location. The remove function doc I'm reading only allows passing the value of the object). Edit: The location of the crash isn't always the same, but it occurs because of this code (i.e. if I revert it, acts normally). What causes a variably timed delayed crash? I do not want the object found to be destroyed. GameObject* GameObjectManager::DetectCollision( const GameObject * gameObject ) { const sf::FloatRect &mainObj = gameObject->GetCollisionBox(); for ( GameObjItr gameObj = m_gameObjects.begin(); gameObj != m_gameObjects.end(); gameObj++ ) { if ( *gameObj && *gameObj != gameObject ) { const sf::FloatRect &otherObj = ( *gameObj )->GetCollisionBox(); if( mainObj.Intersects( otherObj ) ) { m_gameObjects.splice( m_gameObjects.end(), m_gameObjects, gameObj ); //<-------- return m_gameObjects.back(); //<------------- } } } return NULL; } Edit Found the bug, when moving the object to the end of the list, caused infinite loop between 2 GameObjects colliding. Sorry, couldn't have been deciphered from code posted.
When you say: m_gameObjects.erase( gameObj ); the destructor for the thing contained in the list being erased (if it has one) will be called. It's not clear from your question what the type of this thing is, or if this destructor call is expected.
3,232,714
3,232,818
Why is my function returning wrong values?
Possible Duplicate: question about leading zeros As in stackoverflow.com/questions/3232534/question-about-leading-zeros. Number of trailing zeros, binary search from Hacker's Delight: #include <iostream> using namespace std; int ntz(unsigned x){ int n; if ( x==0) return 32; n=1; if ((x & 0x0000FFFF))==0) {n=n+16; x=x>>16;} if ((x & 0x000000ff)==0) {n=n+8;x>>=8;} if ( x &0x0000000F)==0) {n=n+4; x>>=4;} if ((x & 0x00000003)==0) { n=n+2; x>>=2;} return n-(x &1); } int main(){ unsigned x; cin>>x; cout<<ntz(x)<<endl; return 0; } When i enter 8 it return 8 and when I enter 9 the same result why?
Firstly, your code doesn't compile. The parentheses in lines 9 and 11 are not balanced correctly. That said, after fixing the errors and compiling, I get the following results: $ ./a.out 8 3 $ ./a.out 9 0
3,232,822
3,249,833
Linking with multiple versions of a library
I have an application that statically links with version X of a library, libfoo, from thirdparty vendor, VENDOR1. It also links with a dynamic (shared) library, libbar, from a different thirdparty vendor, VENDOR2, that statically links version Y of libfoo from VENDOR1. So libbar.so contains version Y of libfoo.a and my executable contains version X of libfoo.a libbar only uses libfoo internally and there are no libfoo objects passed from my app to libbar. There are no errors at build time but at runtime the app seg faults. The reason seems to be that version X uses structures that have a different size they version Y and the runtime linker seems to be mixing up which get used by which. Both VENDOR1 & VENDOR2 are closed source so I cannot rebuild them. Is there a way to build/link my app such that it always resolves to version X and libbar alway resolves to version Y and the two never mix?
Thanks for all the responses. I have a solution that seem to be working. Here's the problem in detail with an example. In main.c we have: #include <stdio.h> extern int foo(); int bar() { printf("bar in main.c called\n"); return 0; } int main() { printf("result from foo is %d\n", foo()); printf("result from bar is %d\n", bar()); } In foo.c we have: extern int bar(); int foo() { int x = bar(); return x; } In bar.c we have: #include <stdio.h> int bar() { printf("bar in bar.c called\n"); return 2; } Compile bar.c and foo.c: $ gcc -fPIC -c bar.c $ gcc -fPIC -c foo.c Add bar.o to a static library: $ ar r libbar.a bar.o Now create a shared library using foo.o and link with static libbar.a $ gcc -shared -o libfoo.so foo.o -L. -lbar Compile main.c and link with shared library libfoo.so $ gcc -o main main.c -L. -lfoo Set LD_LIBRARY_PATH to find libfoo.so and run main: $ setenv LD_LIBRARY_PATH `pwd` $ ./main bar in main.c called result from foo is 0 bar in main.c called result from bar is 0 Notice that the version of bar in main.c is called, not the version linked into the shared library. In main2.c we have: #include <stdio.h> #include <dlfcn.h> int bar() { printf("bar in main2.c called\n"); return 0; } int main() { int x; int (*foo)(); void *handle = dlopen("libfoo.so", RTLD_GLOBAL|RTLD_LAZY); foo = dlsym(handle, "foo"); printf("result from foo is %d\n", foo()); printf("result from bar is %d\n", bar()); } Compile and run main2.c (notice we dont need to explicitly link with libfoo.so): $ gcc -o main2 main2.c -ldl $ ./main2 bar in bar.c called result from foo is 2 bar in main2.c called result from bar is 0 Now foo in the shared library calls bar in the shared library and main calls bar in main.c I don't think this behaviour is intuitive and it is more work to use dlopen/dlsym, but it does resolve my problem. Thanks again for the comments.
3,232,864
3,232,910
Xerces C++: no error for non-existent file
I'm using the Xerces C++ DOM parser to read some XML files in a Visual C++ project. I have a class with a parse() method that is supposed to read and validate my XML source file. This is what the method looks like: #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/framework/LocalFileInputSource.hpp> using namespace std; XERCES_CPP_NAMESPACE_USE unsigned long RulesParser::parse( const wstring &xmlFile ) { if( parserInitialized_ == false ) { try { XMLPlatformUtils::Initialize(); /* initialize xerces */ } catch( XMLException const &e ) { return Status::PARSER_INIT_FAIL; } } parserInitialized_ = true; /* indicate xerces has been successfully initialized */ if( pDOMParser_ != NULL ) { delete pDOMParser_; } pDOMParser_ = new XercesDOMParser; /* create a DOM parser instance */ /* set xerces options */ pDOMParser_->setDoNamespaces( true ); /* enable namespace processing */ pDOMParser_->setDoSchema( true ); /* enable schema processing */ pDOMParser_->setValidationScheme( XercesDOMParser::Val_Always ); /* parser always validates */ pDOMParser_->setValidationSchemaFullChecking( true ); /* enable full schema checking */ auto_ptr< LocalFileInputSource > srcFile; /* XML source file loader */ try { srcFile.reset( new LocalFileInputSource( xmlFile.c_str() ) ); } catch( const XMLException &e ) { return Status::XML_SOURCE_LOAD_ERROR; } /* parse the file */ try { pDOMParser_->parse( *srcFile ); } catch( const XMLException &e ) { return Status::XML_SOURCE_PARSE_ERROR; } catch( const DOMException &e ) { return Status::XML_SOURCE_PARSE_DOM_ERROR; } return Status::OK; } The documentation for LocalFileInputSource says the constructor will throw an XMLException if the path doesn't resolve to a file. However, I can call this method with any arbitrary string and it executes to the end without any exceptions being raised. What am I doing wrong? Also, the documentation for XercesDOMParser::parse() says a SAXException is one of the types of exceptions that it can throw. I find this confusing because from what I understand DOM and SAX parsers are 2 different animals, so why would the DOM parser throw a SAX exception?
See ErrorHandler documentation. You must declare and define a class that inherits from ErrorHandler and implements its virtual methods (or you can extend the HandlerBase class). Then you must call setErrorHandler on your parser instance passing an instance of your error handler, i.e. pDOMParser_->setErrorHandler(your_handler_instance). Example usage from Xerces-C++ trunk samples: rows 231-233 of SAXPrint.cpp. Update: example of custom error handler below. #include <iostream> #include <xercesc/sax/HandlerBase.hpp> XERCES_CPP_NAMESPACE_USE class CustomErrorHandler : public HandlerBase { public: CustomErrorHandler() {} void error(const SAXParseException& e) { handler(e); } void fatalError(const SAXParseException& e) { handler(e); } void warning(const SAXParseException& e) { handler(e); } private: void handler(const SAXParseException& e) { char* message = XMLString::transcode(e.getMessage()); cerr << "line " << e.getLineNumber() << ", column " << e.getColumnNumber() << " -> " << message << "\n\n"; XMLString::release(&message); } };
3,233,054
3,233,114
error: 'INT32_MAX' was not declared in this scope
I'm getting the error error: 'INT32_MAX' was not declared in this scope But I have already included #include <stdint.h> I am compiling this on (g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44) with the command g++ -m64 -O3 blah.cpp Do I need to do anything else to get this to compile? or is there another C++ way to get the constant "INT32_MAX"? Thanks and let me know if anything is unclear!
#include <cstdint> //or <stdint.h> #include <limits> std::numeric_limits<std::int32_t>::max(); Note that <cstdint> is a C++11 header and <stdint.h> is a C header, included for compatibility with C standard library. Following code works, since C++11. #include <iostream> #include <limits> #include <cstdint> struct X { static constexpr std::int32_t i = std::numeric_limits<std::int32_t>::max(); }; int main() { switch(std::numeric_limits<std::int32_t>::max()) { case std::numeric_limits<std::int32_t>::max(): std::cout << "this code works thanks to constexpr\n"; break; } return EXIT_SUCCESS; } http://coliru.stacked-crooked.com/a/4a33984ede3f2f7e
3,233,078
3,233,081
How does an exception specification affect virtual destructor overriding?
The C++ Standard states the following about virtual functions that have exception specifications: If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the exception-specification of the base class virtual function (C++03 §15.4/3). Thus, the following is ill-formed: struct B { virtual void f() throw() { } // allows no exceptions }; struct D : B { virtual void f() { } // allows all exceptions }; (1) Does this rule apply to destructors? That is, is the following well-formed? struct B { virtual ~B() throw() { } }; struct D : B { virtual ~D() { } }; (2) How does this rule apply to an implicitly declared destructor? That is, is the following well-formed? struct B { virtual ~B() throw() { } }; struct D : B { // ~D() implicitly declared }; While in the general case one should never write an exception specification, this question has practical implications because the std::exception destructor is virtual and has an empty exception specification. Since it is good practice not to allow an exception to be thrown from a destructor, let's assume for the sake of simplifying any examples that a destructor either allows all exceptions (that is, it has no exception specification) or it allows no exceptions (that is, it has an empty exception specification).
(1) Does this rule apply to destructors? Yes, this rule applies to destructors (there is no exception to the rule for destructors), so this example is ill-formed. In order to make it well-formed, the exception specification of ~D() must be compatible with that of ~B(), e.g., struct B { virtual ~B() throw() { } }; struct D : B { virtual ~D() throw() { } }; (2) How does this rule apply to implicitly declared special member function? The C++ Standard says the following about implicitly declared special member functions: An implicitly declared special member function shall have an exception-specification. If f is an implicitly declared default constructor, copy constructor, destructor, or copy assignment operator, its implicit exception-specification specifies the type-id T if and only if T is allowed by the exception-specification of a function directly invoked by f’s implicit definition; f shall allow all exceptions if any function it directly invokes allows all exceptions, and f shall allow no exceptions if every function it directly invokes allows no exceptions (C++03 §15.4/13). What functions are directly invoked by an implicitly declared destructor? After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct members, the destructors for X’s direct base classes and, if X is the type of the most derived class, its destructor calls the destructors for X’s virtual base classes (C++03 §12.4/6; reformatted for easier reading). So, an implicitly declared destructor has an exception specification that allows any exceptions allowed by any of those destructors. To consider the example from the question: struct B { virtual ~B() throw() { } }; struct D : B { // ~D() implicitly declared }; The only destructor called by the implicitly declared ~D() is ~B(). Since ~B() allows no exceptions, ~D() allows no exceptions and it is as if it were declared virtual ~D() throw(). This exception specification is obviously compatible with ~B()'s, so this example is well-formed. As a practical example of why this matters, consider the following: struct my_exception : std::exception { std::string message_; }; ~string() allows all exceptions, so the implicitly declared ~my_exception() allows all exceptions. The base class destructor, ~exception(), is virtual and allows no exceptions, so the derived class destructor is incompatible with the base class destructor and this is ill-formed. To make this example well-formed, we can explicitly declare the destructor with an empty exception specification: struct my_exception : std::exception { virtual ~my_exception() throw() { } std::string message_; }; While the rule of thumb is never to write an exception specification, there is at least this one common case where doing so is necessary.
3,233,290
3,577,325
Filtering out namespace errors when parsing partial XML via libxml2 in C++
I have the need to parse partial XML fragments (which are presented as std::string), such as this one: <FOO:node>val</FOO:node> as xmlDoc objects in libxml2, and because these are fragments, I keep getting the namespace error : Namespace prefix FOO on node is not defined errors spit out into STDERR. What I am looking for is for either a way to filter just these namespace warnings out or parse the XML fragment straight into a xmlNode object. I think some sort of hacking around with initGenericErrorDefaultFunc() may be in order to go the first way, but the documentation for libxml2 is absolutely atrocious. I would frankly prefer to go with the 2nd approach because it would require no error hacking and the node would be already aware of the namespace, but I don't think it's possible because the node has to have a root and XML fragments are not guaranteed to have only one root. I just need some guidance here of how to rid myself of the namespace error warning. Thank you very much.
Building on what @Potatoswatter said... can you create a context for the fragments? E.g. concatenate <dummyRoot xmlns:FOO="dummy-URI"> in front of your fragment, and </dummyRoot> afterward, then pass the concatenated string to xmlParseMemory(). Alternatively, why don't you use xmlParseInNodeContext(), which lets you pass in a node to use as context (including namespaces), and the content can be any Well Balanced Chunk (e.g. multiple elements with no single root element). Either method requires that you know, or can scan to find out, the set of all possible namespace prefixes that the fragment may use.
3,233,369
3,233,384
About returning references to objects
No, this isn't about the mistake everyone makes of passing locals. I'm just trying to understanding returning a reference to an object you pass in (I'm reading through primer). So if I have a function like this: const foo & foo::function2(const foo & val) const { using namespace std; return *this; } and then I'm in main doing this: foo object1; object1.someproperty = 7; foo object2 = object1.function2(object1); object2.someproperty = 5; cout << &object1 << endl; cout << &object2 << endl; When I return by reference, shouldn't object2 have the same address (and properties) as object1? Shouldn't changing "someproperty" in one object alter the value in the other? Or, does returning a reference to an object simply copy over the values into the new object? It seems like the same thing is going on as if I just said that I was going to return a foo object instead of a reference to one.
foo object2 = object1.function2(object1); function2() returns a reference to object1; the foo copy constructor is then invoked to copy object1 into object2, because object2 is declared as a foo object. If you declared object2 as a const reference instead: const foo& object2 = object1.function2(object1); then object2 would be a reference to object1.
3,233,440
3,233,530
How to include a template member in a class?
I am attempting to make a class that has a template object member inside of it. For example mt_queue_c<int> m_serial_q("string"); However, when I do this it fails to compile. If I move this line outside of the class definition so that it becomes a global object, it compiles fine. I condensed the code into the smallest possible fail unit as shown below (yes, it won't make sense because other members variables and functions are missing...) #include <deque> #include <queue> #include <pthread.h> #include <string> #include <iostream> template <class T, class Container = std::deque<T> > class mt_queue_c { public: explicit mt_queue_c(const std::string &name, const Container &cont = Container()) : m_name(name), m_c(cont) {}; virtual ~mt_queue_c(void) {}; protected: // Name of queue, used in error messages. std::string m_name; // The container that manages the queue. Container m_c; }; // string object for a test std::string test2("foobar"); // Two tests showing it works as a global mt_queue_c<char> outside1("string"); mt_queue_c<char> outside2(test2); // Two failed attempts to include the object as a member object. class blah { mt_queue_c<int> m_serial_q("string"); // this is 48 mt_queue_c<char> m_serial_q2(test2); // this is 50 }; // Adding main just because. int main () { std::cout << "Hello World" << std::endl; } When I do this the error results I receive are: make g++ -m32 -fPIC -Werror -Wall -Wunused-function -Wunused-parameter -Wunused-variable -I. -I/views/EVENT_ENGINE/LU_7.0-2/server/CommonLib/include -I/views/EVENT_ENGINE/LU_7.0-2/server/Common/Build/Include -g -c -o ${OBJ_DIR}/testTemp.o testTemp.cxx testTemp.cxx:48: error: expected identifier before string constant testTemp.cxx:48: error: expected ',' or '...' before string constant testTemp.cxx:50: error: 'test2' is not a type make: *** [/views/EVENT_ENGINE/LU_7.0-2/server/applications/event_engine/Obj/testTemp.o] Error 1 What am I doing wrong? How can one 'embed' a template in a class given that we want the template type to always be the same for a particular class? Thanks in advance for your help.
This has nothing to with templates in particular - you can't initialize non-static members directly in the class definition (C++03, §9.2/4): A member-declarator can contain a constant-initializer only if it declares a static member (9.4) of const integral or const enumeration type, see 9.4.2. If you want to explicitly initialize data members, use the constructors initializer-list: blah::blah() : m_serial_q("string") {}
3,233,445
3,233,462
Is there a way to do this?
Here is my issue. I have a std::vector<POINTFLOAT> Which stores verticies. The issue is that Vertex buffer objects take in a pointer to an array of float. Therein lies my problem. I cannot give it an array of pointfloat. Is there a way that I could instead push pointers to the individual components of each vertex without pushing in copies? basically instead of it being: vec[0].x vec[0].y vec[1].x vec[1].y It becomes newvec[0] newvec[1] newvec[2] newvec[3] I thought of making a std::vector<float*> but I don't think opengl would like this. Is there a way to do this without copying data? Thanks Instead of having to copy data for point.x, point.y, I want OpenGL to get its data from the original vector so basically when openGL would get vec[0] it would actually get pointvec[0].x but it needs to act like when passing by reference, no pointed members so Opengl cant do *vec[0]
You can write something like this, ie you have a std::vector which you fill with vertices, and then you call a function (eg an openGL function) which takes a float*. Is that what you want? void some_function(float* data) { } ... std::vector<float> vec; vec.push_back(1.2); // x1 vec.push_back(3.4); // y1 vec.push_back(5.6); // x2 vec.push_back(7.8); // y2 some_function(&vec[0]); EDIT: This will also work, because the floats are laid out the same in memory: struct POINTFLOAT { float x; float y; }; void some_function(float* data) { } ... std::vector<POINTFLOAT> vec; vec.resize(2); vec[0].x = 1.2; // x1 vec[0].y = 3.4; // y1 vec[1].x = 5.6; // x2 vec[1].y = 7.8; // y2 some_function((float*)(&vec[0]));
3,233,471
3,234,026
Tool to Map #include's
Is there a tool available which will take a set of source files and map (in graphic fashion) how they are linked via #include? I would like to see where there are any circular references.
Red Hat source navigator. Strongly recommended.
3,233,513
3,233,521
change value from array
int main() { int Count, Sum = 0; int Group[10]; cout << "-303 to stop\n"; for(Count = 0; Count < 10; Count++) { cout << "Enter a value: "; cin >> Group[Count]; if(Group[Count] == -303) break; } int T; for(T = 0; T < Count; T++) Sum += Group[T]; for(T = 0; T < Count; T++) cout << "Value[" << T << "]= " << Group[T] << endl; } How can I change each of the values from this array? Suppose I want to multiply each value by 2 for example.
Well, just like you can read from Group[T] to print it on the screen, you can assign to Group[T]. So, for example: for(T = 0; T < Count; T++) Group[T] *= 2;
3,233,693
3,234,188
Call a function twice with Assembly and C++
I have a code that changes the function that would be called, to my new function, but I don't want to call only my new function, I also want to call the old one. This is an example, so you can understand what I'm saying: If I disassemble my .exe, I will look at this part: L00123456: mov eax, [L00654321] //doesn't matter mov ecx, [eax+1Ch] //doesn't matter push esi //the only parameter 0x123 call SUB_L00999999 //this is the function I wanna overwrite //... (0x123 is the address of that line) So, I used this code: DWORD old; DWORD from = 0x123; DWORD to = MyNewFunction; VirtualProtect(from, 5, PAGE_EXECUTE_READWRITE, &old); DWORD disp = to - (from + 5); *(BYTE *)(from) = 0xE8; *(DWORD *)(from + 1) = (DWORD)disp; Now, instead of calling SUB_L00999999, it calls MyNewFunction... So... any ideas on how can I still call the old function? I tried things like this (in many ways), but it crashes my application: int MyNewFunction(int parameter) { DWORD oldfunction = 0x00999999; _asm push parameter _asm call oldfunction } Notes: I use Visual Studio C++ 2010 and these codes are in a .dll loaded in an .exe. Thanks.
I had a problem like this a while back. Anyway, _asm call dword ptr [oldfunction] worked for me.
3,233,708
3,235,091
share queue between parent and child process in c++
I know there are many way to handle inter-communication between two processes, but I'm still a bit confused how to deal with it. Is it possible to share queue (from standard library) between two processes in efficient way? Thanks
Simple answer: Sharing an std::queue by two processes can be done but it is not trivial to do. You can use shared memory to hold the queue together with some synchronization mechanism (usually a mutex). Note that not only the std::queue object must be constructed in the shared memory region, but also the contents of the queue, so you will have to provide your own allocator that manages the creation of memory in the shared region. If you can, try to look at higher level libraries that might provide already packed solutions to your process communication needs. Consider Boost.Interprocess or search in your favorite search engine for interprocess communication.
3,233,727
3,279,395
What has to be Glib::init()'ed in order to use Glib::wrap?
So I'm trying to make use of a GtkSourceView in C++ using GtkSourceViewmm, whose documentation and level of support give me the impression that it hasn't been very carefully looked at in a long time. But I'm always an optimist :) I'm trying to add a SourceView using some code similar to the following: Glib::RefPtr<gtksourceview::SourceLanguageManager> source_language_manager = gtksourceview::SourceLanguageManager::create(); Glib::RefPtr<gtksourceview::SourceLanguage> source_language = Glib::wrap(gtk_source_language_manager_guess_language(source_language_manager->gobj(), file, NULL)); Glib::RefPtr<gtksourceview::SourceBuffer> source_buffer = gtksourceview::SourceBuffer::create(source_language); gtksourceview::SourceView* = m_source_view = new gtksourceview::SourceView(source_buffer); m_vbox.pack_start(*m_source_view); Unfortunately, it spits out the warning (algoviz:4992): glibmm-WARNING **: Failed to wrap object of type 'GtkSourceLanguage'. Hint: this error is commonly caused by failing to call a library init() function. and when I look at it in a debugger, indeed the second line above (the one with the Glib::wrap()) is returning NULL. I have no idea why this is, but I tried to heed the warning by adding Glib::init() to the begining of the program, but that didn't seem to help at all either. I've tried Google'ing around, but have been unsuccessful. Does anyone know what Glib wants me to init in order to be able to make that wrap call? Or, even better, does anyone know of any working sample code that uses GtkSourceViewmm (not just regular GtkSourceView)? I haven't been able to find any actual sample code, not even on Google Code Search. Thanks!
It turns out, perhaps not surprisingly, that what I needed to init was: gtksourceview::init(); After this, I ran into another problem with one of the parameter to gtksourceview::SourceLanguageManager, but this was caused by a genuine bug which I subsequently reported and was promptly fixed. So everything's working great now!
3,233,766
3,233,786
Using both .so and .dll on Windows
I am writing a program in windows in C++ in which users will be able to compile extensions in the form of dynamic-link libraries (windows), or shared object files (linux). On windows, you use the LoadLibrary function to load a dll. Is it possible to do the same for .so files on windows and vice versa, load .dlls on linux?
The short answer is "No" That is not about loading but about internal format of dynamic library like expected entry points. Each operating system support it's own format. Hence it won't work. DLL is a PE executable (as are exe on windows) .so is usually an ELF format (like most modern executables on Linux/Unix). However on Linux there is some support for PE executable through Wine, and Wine program can use DLL. But that's probably not what you are looking for. On Windows there is also some support of ELF format through cygwin, and there is also some compilers that can load coff format (the one used on Unix before ELF). I used DJGPP for this a long time ago.
3,233,987
3,235,024
Deleting a reference
Is this valid? An acceptable practice? typedef vector<int> intArray; intArray& createArray() { intArray *arr = new intArray(10000, 0); return(*arr); } int main(int argc, char *argv[]) { intArray& array = createArray(); //.......... delete &array; return 0; }
The behavior of the code will be your intended behavior. Now, the problem is that while you might consider that programming is about writing something for the compiler to process, it is just as much about writing something that other programmers (or you in the future) will understand and be able to maintain. The code you provided in many cases will be equivalent to using pointers for the compiler, but for other programmers, it will just be a potential source of errors. References are meant to be aliases to objects that are managed somewhere else, somehow else. In general people will be surprised when they encounter delete &ref, and in most cases programmers won't expect having to perform a delete on the address of a reference, so chances are that in the future someone is going to call the function an forget about deleting and you will have a memory leak. In most cases, memory can be better managed by the use of smart pointers (if you cannot use other high level constructs like std::vectors). By hiding the pointer away behind the reference you are making it harder to use smart pointers on the returned reference, and thus you are not helping but making it harder for users to work with your interface. Finally, the good thing about references is that when you read them in code, you know that the lifetime of the object is managed somewhere else and you need not to worry about it. By using a reference instead of a pointer you are basically going back to the single solution (previously in C only pointers) and suddenly extra care must be taken with all references to figure out whether memory must be managed there or not. That means more effort, more time to think about memory management, and less time to worry about the actual problem being solved -- with the extra strain of unusual code, people grow used to look for memory leaks with pointers and expect none out of references. In a few words: having memory held by reference hides from the user the requirement to handle the memory and makes it harder to do so correctly.
3,234,042
3,234,316
Is there a (Linux) g++ equivalent to the /fp:precise and /fp:fast flags used in Visual Studio?
Background: Many years ago, I inherited a codebase that was using the Visual Studio (VC++) flag '/fp:fast' to produce faster code in a particular calculation-heavy library. Unfortunately, '/fp:fast' produced results that were slightly different to the same library under a different compiler (Borland C++). As we needed to produce exactly the same results, I switched to '/fp:precise', which worked fine, and everything has been peachy ever since. However, now I'm compiling the same library with g++ on uBuntu Linux 10.04 and I'm seeing similar behavior, and I wonder if it might have a similar root cause. The numerical results from my g++ build are slightly different from the numerical results from my VC++ build. This brings me to my question: Question: Does g++ have equivalent or similar parameters to the 'fp:fast' and 'fp:precise' options in VC++? (and what are they? I want to activate the 'fp:precise' equivalent.) More Verbose Information: I compile using 'make', which calls g++. So far as I can tell (the make files are a little cryptic, and weren't written by me) the only parameters added to the g++ call are the "normal" ones (include folders and the files to compile) and -fPIC (I'm not sure what this switch does, I don't see it on the 'man' page). The only relevant parameters in 'man g++' seem to be for turning optimization options ON. (e.g. -funsafe-math-optimizations). However, I don't think I'm turning anything ON, I just want to turn the relevant optimization OFF. I've tried Release and Debug builds, VC++ gives the same results for release and debug, and g++ gives the same results for release and debug, but I can't get the g++ version to give the same results as the VC++ version.
Excess register precision is an issue only on FPU registers, which compilers (with the right enabling switches) tend to avoid anyway. When floating point computations are carried out in SSE registers, the register precision equals the memory one. In my experience most of the /fp:fast impact (and potential discrepancy) comes from the compiler taking the liberty to perform algebraic transforms. This can be as simple as changing summands order: ( a + b ) + c --> a + ( b + c) can be - distributing multiplications like a*(b+c) at will, and can get to some rather complex transforms - all intended to reuse previous calculations. In infinite precision such transforms are benign, of course - but in finite precision they actually change the result. As a toy example, try the summand-order-example with a=b=2^(-23), c = 1. MS's Eric Fleegal describes it in much more detail. In this respect, the gcc switch nearest to /fp:precise is -fno-unsafe-math-optimizations. I think it's on by default - perhaps you can try setting it explicitly and see if it makes a difference. Similarly, you can try explicitly turning off all -ffast-math optimizations: -fno-finite-math-only, -fmath-errno, -ftrapping-math, -frounding-math and -fsignaling-nans (the last 2 options are non default!)
3,234,141
3,234,201
WinAPI Write "Edit" Dialog to Pipe (Error: Stack around variable 'x' was corrupted)
It seems I figured out most of my problems by simply multi-threading my application! However, I am running into a little bit of an error: "Stack around variable 'x' was corrupted." It works properly (after hitting abort on the Debug Error), but obviously I cannot have an error everytime someone runs the application. So here is the relevant code. It is the callback to one of my worker threads. DWORD WINAPI Arc_writePipe(LPVOID threadParam) { Arc_Redirect ar; DWORD dwWrote; CHAR chBuf[BUFSIZE]; HANDLE hPipe = (HANDLE)threadParam; HWND g1 = FindWindow("GUI",NULL); HWND dlg = GetDlgItem(g1,IDO_WORLDOUT); //int nLength = GetWindowTextLength(GetDlgItem(g1,IDO_WORLDINPUT)); while(bRunThread) { if(GetDlgItemText(g1,IDO_WORLDINPUT,chBuf,BUFSIZE)) { chBuf[BUFSIZE] = '\0'; if(!WriteFile(hPipe,chBuf,BUFSIZE,&dwWrote,NULL)) { //SetDlgItemText(g1,IDO_WORLDINPUT,NULL); // This is to reset text when done sending to input if(GetLastError() == ERROR_NO_DATA) break; // Normal :) else MessageBox(g1,"Error: Could not WriteFile();","Error",MB_ICONERROR); } } } return 1; } Does anyone have any ideas on why this error keeps occurring? I am not getting any GetLastError() output other than "ERROR_NO_DATA," after the data is written so I am assuming it has something to do with my WriteFile(); function in conjunction with the BUFSIZE (defined at 0x1000). So basically, I am doing something wrong. Does anyone know perhaps a better way to get information from an edit dialog and write it to a pipe? Thanks so much for your help! Regards,Dennis M.
I don't know where the corruption is happening, so I don't know what exactly the problem is. However, the following line is wrong: chBuf[BUFSIZE] = '\0'; You declared chBuf with the size BUFSIZE which means that the index BUFSIZE is actually outside of the array. This will result in stack corruption. What you really need to do is chBuf[BUFSIZE - 1] = '\0';
3,234,468
3,234,623
How are controls put in the caption bar?
I noticed Firefox 4, Opera and Chrome, and IE 7/8 put buttons and controls in the title/caption bar, how is this done? Thanks http://img199.imageshack.us/img199/3307/slayerf.png alt text http://img199.imageshack.us/img199/3307/slayerf.png
What they probably do is turn the caption bar off entirely (by excluding the WS_CAPTION window style), add a glass area to the top of the window, and then draw their own controls. See http://msdn.microsoft.com/en-us/magazine/cc163435.aspx for more on glass.
3,234,762
3,235,087
Using bitset in place of using hand written bit manipulation code?
Is there any performance loss/gain using bitset in place where hand written? How to build the following using a bitset at runtime make all the bits between 2 and 5 as zero i.e., 11110011.
The easiest solution to your second question would be to use another bitset. void makebitszero(bitset<8>& b) { // Everything but bits 3 and 4 (between 2 and 5). static const bitset<8> mask = ~bitset<8>(12); b &= mask; } It takes a bit of math to come up with an expression for mask given two bit positions. [edit] Ok, here's the math. The trick is that (1UL << X) -1 is a sequence of X ones. E.g. 3 => 00000111. Hence, (1<<5) - (1<<3) = 00011111 - 00000111 -1 + 1 = 00011000 (bits 3 and 4). Thus in code: template<int i, int j, int N> void makeBitsZero(bitset<N>& b) { // Everything from bit i up to but not including bit j (i < j) static const bitset<N> mask = ~bitset<N>(1UL<<j) - (1UL<<i)); b &= mask; }
3,234,875
3,234,913
question about Multiply high signed
#include <iostream> using namespace std; int mulths(int u,int v) { unsigned u0,v0,w0; int u1,v1,w1,w2,t; u0 = u & 0xFFFF; u1 = u >> 16; v0 = v & 0xFFFF; v1 = v >> 16; w0 = u0 * v0; t = u1 * v0 + (w0 >> 16); w1 = t & 0xFFFF; w2 = t >> 16; w1 = u0 * v1 + w1; return u1 * v1 + w2 + (w1 >> 16); } int main() { int u,v; cin >> u >> v; cout << mulths(u, v) << endl; return 0; } does it returns product of two number yes or it returns most significant bit? beacuse when i enter 5 and 7 and it return 0
"Multiply high" returns the high word of the result. E.g. if ints are 32 bits then when you multiply two 32 bit ints you get a 64 bit result. So you can think of this as a 32 bit (signed) high word and a 32 bit (unsigned) low word. E.g. 0x01234567 x 0x456789AB = 0x004EF78252247ACD. High word (signed) = 0x004EF782, low word (unsigned) = 0x52247ACD. For your test the values of 5 and 9 are too small and so the high word will be zero. Try larger values such as the above to see if you get the correct result, e.g. $ g++ -m32 -Wall mulths.cpp -o mulths $ ./mulths 1000 1000 0 $ ./mulths 100000 100000 2 $ ./mulths 19088743 # 0x01234567 1164413355 # 0x456789AB 5175170 # 0x004EF782 $
3,235,073
3,235,089
How do I format c++ comments properly?
Could anyone please suggest a proper format of comments I should use in a C++ project? I think that there is some analog of javadoc format, but I can't find which one. Is there any de-facto standard of that kind? Thanks!
Doxygen is used rather frequently for C++ projects (Doxygen supports other languages as well). You can use Doxygen-style comments as a starting point (here are some examples). Just be consistent.
3,235,228
3,235,433
namespace same name as function
I have this in a header: double commonFunction( ... ) { /*...*/ } namespace F2 { double impactFactor( ... ) { /*...*/ } double func( ... ) { /*...*/ } double F2( ... ) { /*...*/ } } namespace FL { double impactFactor( ... ) { /*...*/ } double func( ... ) { /*...*/ } double FL( ... ) { /*...*/ } } And I would like to access the F2 and FL functions from the global namespace. I tried adding this to the end of the header (or after an include, doesn't matter): using F2::F2; using FL::FL; I'm sure this works when the function names differ from the namespace names, but why does this not work and how can I fix it? Thanks PS: I can't put the functions outside their namespace, because that would lead to a redefined symbol (F2 and FL, as both namespace and function). UPDATE: for those cursing me, here's what I did. Since this is a scientific formula header, and a good short namespace name is hard to find I named the namespaces F2 and FL and the functions themselves f2 and fL.
Because, using brings every declaration with given name into scope, so if you already have two or more declaration with one name (in this case namespace f1), it will complain. And it has nothing to do with the name of the namespace and function being the same. Even this will generate the same error: namespace foo { void not_foo(){}; } namespace not_foo { void foo(){} } using not_foo::foo;
3,235,424
3,265,148
C++ Sockets Send() Thread-Safety
I am coding sockets server for 1000 clients maxmimum, the server is about my game, i'm using non-blocking sockets and about 10 threads that receive data simultaneously from different sockets (first thread receives from 0-100,second from 101-200 and so on..) but if thread 1 wants to send data to all 1000 clients and thread 2 also wants to send data to all 1000 clients at the same time, is that safe? are there any chances of the data being messed in the other (client) side? if yes, i guess the only problem that can happen is that sometimes client would receive 2 or 10 packets as 1 packet, is that correct? if yes, is there any solution to that :(
The usual pattern of dealing with many sockets is to have a dedicated thread polling for I/O events with select(2), poll(2), or better kqueue(2) or epoll(4) (depending on the platform) acting as socket event dispatcher. The sockets are usually handled in non-blocking mode. Then one might have pool of threads reacting to the events and either do reads and writes directly or via lower level buffers/queues. All sorts of techniques are applicable here - from queues to event subscription whiteboards. It gets tricky with multiplexing accepts/reads/writes/EOFs on the I/O level and with event arbitration on the application level. Several libraries like libevent and boost::asio help structure the lower level (the ACE library is also in this space, but I'd hate recommending it to anybody). You would have to come up with application-level protocols and state machines yourself (again boost::statechart might be of help). Some good links to get better understanding of what you are up against (this is probably the millionth time they are mentioned here on SO): The C10K problem High-Performance Server Architecture Apologies for not offering a concrete solution, but this is a very wide design question and most decisions depend heavily on the context (lots of fun though). Hope this helps a bit.
3,235,685
3,235,933
Why doesn't this segfault
I stumbled across something "interesting" and I cant put my finger why the behaviour isn't coherent. Check this code. char buf[100]; sprint(buf,"%s",bla); Simple, right. It's easy to understand what is going on when bla is a NULL pointer. This should always segfault right!? In one machine the executable segfaults, on another (my development machine), it's just business as usual. My devel PC is running Windows7 and I'm compiling with gcc/MingW. The computer where this is crashing is XP and it does have Visual studio 6 installed. Why doesn't this crash on my PC?
ISO C99: 7.19.6.3 The printf function Synopsis #include <stdio.h> int printf(const char * restrict format, ...); The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf. 7.19.6.1 The fprintf function 7.19.6.1.9 If a conversion specification is invalid, the behavior is **undefined**. If any argument is not the correct type for the corresponding conversion specification, the behavior is **undefined**. So your code invokes Undefined Behavior [(ISO C99 3.4.3) behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes **no requirements**] This should always segfault right!? Not necessarily, Undefined Behavior means anything can happen.
3,235,778
3,235,812
capture a call stack and have it execute in a different thread
I need to write a logging api which does the actual logging on a seperate thread. i.e. I have an application which wants to log some information. It calls my API and the api captures all the arguments etc and then hands that off to a seperate thread to be logged. The logger api accepts variadic arguments and therefore my initial thoughts were to capture the whole call stack and somehow hand it to the thread whcih will do the logging. I'm reasonable happy that I can capture the call stack. However I'm not sure how I'd pass this call stack off to another method. I'm using g++ on linux and it may also have to work with Sun's CC v12 on solaris. Any ideas.
You could capture a fixed amount of bytes on the call stack, but you have to copy all that memory even when it's not necessary and put it on a queue of some sort to pass it to the logging thread. Seems like a lot of work to get working, and quite inefficient. I assume you're using a separate logging thread to make the logging API more efficient. It's quite probable that it's more efficient in this case to have the logging API extract the variadic parameters, convert them into a simpler representation (for example the string to be logged) and queue that. Note also that a good logging API shouldn't block, so I'd advise a lock-free queue between the logging API and the logging thread.
3,235,799
3,235,859
How can we use any C library inside our C++ code?
How can we use any C library inside our C++ code? (Can we? Any tuts on that?) (I use VS10 and now talking about libs such as x264 and OpenCV)
Well you can use any C library from your C++ code. That's one the cool thing with C++ :-) You just have to include the libraries headers in your C++ code and link with the libraries you use. Any good library handles its header inclusion from C++. If it is not the case you have to do it yourself with things like : #ifdef __cplusplus extern "C" { #endif #include "c_header.h" #ifdef __cplusplus } #endif Edit: As Mike said, the ifdef parts are only needed if you do not know if your file will be used with C or C++. You can keep them if the file is a header of an API header for example. By the way, opencv handles the inclusion by C or C++ (thus you already have the #ifdef part in opencv headers). I do not know for x264 ... my2cents
3,235,815
3,237,465
CreateCompatibleBitmap failing on Windows mobile 6
I'm porting an application from Windows Mobile 2003 to Windows Mobile 6, under Visual Studio 2008. The target device has a VGA resolution screen, and I was surprised to find that the following code fails; CClientDC ClientDC(this); CRect Rect; GetClientRect(&Rect); int nWidth = Rect.Width(),nHeight = Rect.Height(); CBitmap Temp; if (!Temp.CreateCompatibleBitmap(&ClientDC,nWidth,nHeight)) { LogError(elvl_Debug,_T("Error creating bitmap (%s)"),LastSysError()); } else { BITMAP bmpinfo; Temp.GetBitmap(&bmpinfo); } The return code from CreateCompatibleBitmap is 8, which translates to 'Not enough memory to process command. nWidth is 350, nHeight is 400, and the display is 16 bits per pixel, so my bitmap is a whopping 280K. The device I'm using has 256mb of program memory, and I've told the linker to reserve 4mb of stack and 64mb of heap. Any ideas what I'm doing wrong, and more importantly a solution? I've been using code similar to the above on Windows CE since CE 2.1 with no problems. Edit: As per Josh Kelly's post, I moved to device independent bitmaps which works fine on the device. Code is now something like this CClientDC ClientDC(this); CRect Rect; GetClientRect(&Rect); int nWidth = Rect.Width(),nHeight = Rect.Height(); BITMAPINFOHEADER bmi = { sizeof(bmi) }; bmi.biWidth = nWidth; bmi.biHeight = nHeight; bmi.biPlanes = 1; bmi.biBitCount = 8; HDC hdc = CreateCompatibleDC(NULL); BYTE* pbData = 0; HBITMAP DIB = CreateDIBSection(hdc, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&pbData, NULL, 0); CBitmap *pTempBitmap = CBitmap::FromHandle(DIB);
I haven't done any Windows CE / Windows Mobile programming, but I have dealt with a similar problem (CreateCompatibleBitmap failing with ERROR_NOT_ENOUGH_MEMORY) in desktop Windows. Apparently, from what I've been able to tell from looking around online, Windows may enforce global limitations on the available memory for device dependent bitmaps. (For example, some video drivers may choose to store device dependent bitmaps in video RAM, in which case you're limited by how much RAM is on your video card.) See, for example, this thread. From what I can tell, these limits are determined by the individual video cards or drivers; some computers' storage may be effectively unlimited, others may have strict limits. One solution is to use device independent bitmaps instead, even though they have a slight performance penalty.
3,235,915
3,235,966
Why are IsEqualGUID() and "operator ==" for GUID declared to return int?
Windows SDK features IsEqualGUID() function and operator==() for two GUIDs that return BOOL (equivalent to int): // Guiddef.h #ifdef __cplusplus __inline int IsEqualGUID(REFGUID rguid1, REFGUID rguid2) { return !memcmp(&rguid1, &rguid2, sizeof(GUID)); } #else // ! __cplusplus #define IsEqualGUID(rguid1, rguid2) (!memcmp(rguid1, rguid2, sizeof(GUID))) #endif //also in Guiidef.h #ifdef __cplusplus __inline int operator==(REFGUID guidOne, REFGUID guidOther) { return IsEqualGUID(guidOne,guidOther); } #endif What's the point in that int? I understand that C doesn't have bool datatype, but there's an #ifdef __cplusplus around, so this code will only be compiled as C++, so bool will be supported anyway. Having a negation near memcmp() effectively transforms all possible values returned from memcmp() into zero and nonzero. Also there're no user-defined operators in C - only C++ supports them. So the operator== would not compile in C code anyway. Are there any reasons for choosing int instead of bool here?
Because the Windows API exposes IsEqualGUID() as a function returning a BOOL. They need to keep a stable interface. BOOL and bool are different sizes, and the Windows API is designed to be compatible with a variety of languages and compilers. Remember that there are other languages other than C++ that interact with the Windows API. On C and C++, IsEqualGUID() is implemented in terms of memcmp(), but IsEqualGUID() is also implemented in ole32.dll. You can obtain the function from ole32.dll: REFGUID guid1 = IID_IUnknown; REFGUID guid2 = IID_AsyncIUnknown; typedef BOOL (WINAPI *IsEqualGUIDFuncType)(REFGUID, REFGUID); HMODULE h = ::LoadLibrary("ole32.dll"); IsEqualGUIDFuncType f = reinterpret_cast<IsEqualGUIDFuncType> (::GetProcAddress(h, "IsEqualGUID")); if(f != NULL) { if(f(guid1, guid2) != 0) ::printf("true\n"); else ::printf("false\n"); } ::FreeLibrary(h); So even though it's implemented as an inline function in C++, other languages may use the DLL implementation of IsEqualGUID(). The C++ version returns a BOOL so it is consistent with the API.
3,235,916
3,236,027
A way How to Compile C library into .Net dll?
Can we compile C library as .Net dll (containing and opening access to all C libs functions) by just compiling cpp project containing code like extern "C" { #include <library.h> } with /clr:pure argument with VS? (VS10) Or we should do something more trickey?
I found it is the best to use the old style Managed C++ for this. CLR:PURE just wont cut it. Example: extern "C" int _foo(int bar) { return bar; } namespace Bar { public __gc class Foo { public: Foo() {} static int foo(int bar) { return _foo(bar); } }; }; Compile with: /clr:oldSyntax Now you can reference the assebmly, and call Bar.Foo.foo() from .NET.
3,235,927
3,236,024
Reference as key in std::map
Suppose some data structure: typedef struct { std::string s; int i; } data; If I use the field data.s as key when adding instances of data in a map of type std::map<std::string&, data>, do the string gets copied? Is it safe to erase an element of the map because the reference will become invalid? Also do the answers to these questions also apply to an unordered_map? EDIT: This is my current solution... but adding iterator to the map is UGLY: typedef struct { const std::string* s; int i; } data; std::map<std::string, data> map; typedef std::map<std::string, data>::iterator iterator; // add an element to the map iterator add_element(const std::string& s) { std::pair<iterator, bool> p = states.insert(std::make_pair(s, data())); iterator i = p.first; if(p.second) { data& d = (*i).second; d.s = &(*i).first; } return i; }
C++11 Since C++11 reference wrapper is part of standard. #include <functional> std::map<std::reference_wrapper<std::string>, data> Using Boost You may want to take a look at boost.ref. It provides a wrapper that enables references to be used in STL-containers like this: std::map<boost::reference_wrapper<std::string>, data>
3,236,136
3,236,188
Problems with declarations and initializations
I am trying to rewrite a code I have written earlier. The code uses cplex concert API; #include <ilcplex/ilocplex.h> using namespace std; ILOSTLBEGIN int main(){ IloEnv env; IloModel model(env); IloVarArray x(env); IloCplex cplex(model); return 0; } This code (though it doesn't do anything) works... However now i have implemented my own Class and would like to be able to use these functions as well but I don't know how to inizialize them. So this time I have written them in a differnet class called solver. //solver.h #ifndef solver_h #define solver_h #include <ilcplex/ilocplex.h> class solver{ public: IloModel model; IloNumVarArray x; IloRangeArray con; IloCplex cplex; solver(); solver~(); }; #endif Then the cpp file //solver.cpp #include <ilcplex/ilocplex.h> #include <vector> using namespace std; #include "solver.h" ILOSTLBEGIN solver::solver(){ IloEnv env; IloModel model(env); IloVarArray x(env); IloCplex cplex(model); } If i add a function to this class e.g. a function that calls x.add(IloNumVar(env)); In the first example this would add an variable to the x(array), but when I have it in a different class I catch "tring to implement empty handle"... I know I'm doing everything right in the main program, and I also get it to work if I dont have the different Cplex classes in the h.file but then I can only use the same model once and i would want to call the same model several times. Is there something clearly wrong here (Besides the lack of code, destructors, etc...) in the h.file or?
This code: solver::solver(){ IloEnv env; IloModel model(env); IloVarArray x(env); IloCplex cplex(model); } is not initialising your class members - it is creating local variables in the constructor, which will destroyed when the constructor exits. You want something like: solver :: solver( IloEnv & env ) : model( env ), x( env ), cplex( model ) { } then in main: int main() { IloEnv env; solver s( env ); // create solver object }
3,236,199
3,236,586
VS2010 C++ member template function specialization error
I have the following (minimized) code, which worked in VC2005, but no longer works in 2010. template <typename TDataType> class TSpecWrapper { public: typedef typename TDataType::parent_type index_type; public: template <bool THasTriangles> void Spec(index_type& io_index) { std::cout << "False version" << std::endl; } template <> void Spec<true>(index_type& io_index) { std::cout << "True version" << std::endl; } }; It seems that when "index_type" is a dependent type, I always get a C2770: invalid explicit template argument(s) error on the specialization. Note that this code is actually enough to generate the error - an empty main is sufficient to compile it, the template need not even be instantiated. It works fine if index_type is not a dependent type. Any ideas why this is so in VC2010, if this is actually standard behaviour or a bug, and if I can work around it?
Workaround template <bool v> struct Bool2Type { static const bool value = v; }; template <typename TDataType> class TSpecWrapper { public: typedef typename TDataType::parent_type index_type; public: template <bool THasTriangles> void Spec(index_type& io_index) { return SpecHelp(io_index, Bool2Type<THasTriangles>()); } private: void SpecHelp(index_type& io_index, Bool2Type<false>) { std::cout << "False version" << std::endl; } void SpecHelp(index_type& io_index, Bool2Type<true>) { std::cout << "True version" << std::endl; } };
3,236,370
3,236,398
Class type from pointer used as template argument
If a pointer to an user defined type is passed as template argument to a template class, is it possible to get the class type of the argument? template <class T> struct UserType { typedef T value_type; ... }; int main () { typedef std::vector<UserType<double>*> vecType vecType vec; vecType::value_type::value_type m; //how to get the double here? return 0; }
Use traits: template <typename> struct ptr_traits {}; template <typename T> struct ptr_traits<T*> { typedef T value_type; }; ptr_traits<vecType::value_type>::value_type m;
3,236,767
3,236,814
auto_ptr and containers - C++
I'm currently working on a 2D game engine and I've read about auto_ptr's and how you should never put them in standard containers. My engine has this structure: StateManager -- has many --> State's. States are created and allocated in main, outside of the engine. I want the engine to store a list/vector of all the states so I can change between them on command. For example: SomeState *test = new SomeState(); StateManager->registerState(test); Since states die when and only when the application dies, can I use this approach? std::auto_ptr<SomeState> test(new SomeState()); StateManager->registerState(test.get()); // Inside StateManager State *activeState; // State manager then maintains a vector std::vector<State*> stateList; // and upon registerState it adds the pointer to the vector void registerState(State *state) { stateList.push_back(test); } The StateManager should only maintain a vector of pointers to the states, it shouldn't need to take ownership. When I want to change state in the engine, I just change the activeState pointer to point to the desired state which is found in the stateList vector. Is this a bad approach?
Why not use std::vector<State> instead and not worry about storing pointers? It sounds like the list of states is fixed so any iterators will not be invalidated during the lifetime of the program. Alternatively, I've found the Boost Pointer Container library to be useful for this sort of thing.
3,237,201
3,237,238
Pointers to statically allocated objects
I'm trying to understand how pointers to statically allocated objects work and where they can go wrong. I wrote this code: int* pinf = NULL; for (int i = 0; i<1;i++) { int inf = 4; pinf = &inf; } cout<<"inf"<< (*pinf)<<endl; I was surprised that it worked becasue I thought that inf would dissapear when the program left the block and the pointer would point to something that no longer exists. I expected a segmentation fault when trying to access pinf. At what stage in the program would inf die?
Your understanding is correct. inf disappears when you leave the scope of the loop, and so accessing *pinf yields undefined behavior. Undefined behavior means the compiler and/or program can do anything, which may be to crash, or in this case may be to simply chug along. This is because inf is on the stack. Even when it is out of scope pinf still points to a useable memory location on the stack. As far as the runtime is concerned the stack address is fine, and the compiler doesn't bother to insert code to verify that you're not accessing locations beyond the end of the stack. That would be prohibitively expensive in a language designed for speed. For this reason you must be very careful to avoid undefined behavior. C and C++ are not nice the way Java or C# are where illegal operations pretty much always generate an immediate exception and crash your program. You the programmer have to be vigilant because the compiler will miss all kinds of elementary mistakes you make.
3,237,228
3,238,886
Set Focus to a Cocoa Window in Carbon App
I'm trying to create a Cocoa Window within an otherwise Carbon Application (it's an OpenGL API that uses AGL. Can't change it so don't comment on that). Here's a code snippit: WindowRef winref = static_cast<eq::AGLWindow*>(getOSWindow())->getCarbonWindow(); vc = [[SFAttachedViewController alloc] initWithConfig:config]; //loads from view nib NSPoint buttonPoint = NSMakePoint(event.pointerButtonPress.x + [cocoaWrap frame].origin.x, [cocoaWrap frame].size.height - event.pointerButtonPress.y + [cocoaWrap frame].origin.y); MAAttachedWindow *attachedWindow = [[MAAttachedWindow alloc] initWithView:[vc view] attachedToPoint:buttonPoint onSide:side atDistance:0.0f]; // some Matt Gemmell goodness! And I try to show it with one of the following lines: // A) [NSApp runModalForWindow:[attachedWindow retain]]; // makes a white box // B) NSWindow *cocoaWrap = [[NSWindow alloc] initWithWindowRef:winref]; [cocoaWrap addChildWindow:attachedWindow ordered:NSWindowAbove]; // C) [attachedWindow makeKeyAndOrderFront:NSApp]; The window shows, but the focus is never given. I can't edit any of the controls, and everything is grayed out. help!? I tried HIViewRef viewRef; HICocoaViewCreate([vc view], 0, &viewRef); WindowRef attachedRef = (WindowRef)[attachedWindow windowRef]; SetKeyboardFocus(attachedRef, viewRef, kControlNoPart); Thinking it might have been a Carbon/Cocoa thing, but to no avail.
Did you call NSApplicationLoad() before calling Cocoa methods?
3,237,245
3,238,123
dynamic_cast an interface from a shared library which was loaded by lt_dlopen(libtool) doesn't work
This is about plugin features in my program. I need a C++ class(and object) in a plugin could be used by main module through an interface. The interface inheritance like this: typedef struct _rwd_plugin_root_t RWD_PLUGIN_ROOT_T; struct RWD_PLUGIN_API _rwd_plugin_root_t { virtual int add_ref() = 0; virtual int release() = 0; }; typedef struct _rwd_plugin_base_t RWD_PLUGIN_BASE_T; struct RWD_PLUGIN_API _rwd_plugin_base_t : _rwd_plugin_root_t { virtual RWD_PLUGIN_TYPE_T get_plugin_type() = 0; virtual const char * get_plugin_label_a() = 0; virtual const wchar_t * get_plugin_label_w() = 0; }; typedef struct _rwd_autocomplete_plugin_base_t RWD_AUTOCOMPLETE_PLUGIN_BASE_T; struct RWD_PLUGIN_API _rwd_autocomplete_plugin_base_t : _rwd_plugin_base_t { virtual int set_proxy(int type, const char * host, long port) = 0; virtual int set_term(const char * text) = 0; virtual int set_term(const wchar_t * text) = 0; virtual int get_phon(std::vector<std::string> & phons) = 0; ... // omitted it's too long }; Then I have a class in plugin to implement the interface like this: class RWD_PLUGIN_API _rwd_dictcn_t : public _rwd_autocomplete_plugin_base_t { public: _rwd_dictcn_t(); ~_rwd_dictcn_t(); ... // details of implementation omitted The creator in plugin is defined like this: EXTERN_C int RWD_PLUGIN_API create_rwd_plugin(_rwd_plugin_base_t ** pp) { *pp = new _rwd_dictcn_t(); return OK; } At last, I use the creator in main application so as to use the plugin like this: ... lt_dlhandle lh = lt_dlopen(filePath); RWD_PLUGIN_CREATE_FUNC_T pPluginFunc = NULL; if(lh) { pPluginFunc = reinterpret_cast<RWD_PLUGIN_CREATE_FUNC_T>(lt_dlsym(lh, "create_rwd_plugin")); if(pPluginFunc) { RWD_PLUGIN_BASE_T * pBase = NULL; if(OK == (*pPluginFunc)(&pBase)) { RWD_PLUGIN_TYPE_T pluginType = pBase->get_plugin_type(); if(pluginType == RWD_PLUGIN_TYPE_AUTOCOMPELE) { ... RWD_PLUGIN_FUNC_T pPluginInitFunc = reinterpret_cast<RWD_PLUGIN_FUNC_T>(lt_dlsym(lh, "initialize_rwd_plugin")); if(pPluginInitFunc) (*pPluginInitFunc)(NULL); // set proxy RWD_AUTOCOMPLETE_PLUGIN_BASE_T * pAuto = dynamic_cast<RWD_AUTOCOMPLETE_PLUGIN_BASE_T*>(pBase); ... The problem is dynamic_cast always fails and pAuto end up being a nil. However the WIN32 version works fine. The problem happened on linux with autoconf2.61 automake1.10.1 make3.81 g++4.4.4 libtool1.5.26 . I have less experience with linux programming and hope getting help here. Thanks! The full source code could be get on Sourceforge if necessary: svn co https://rdwtwdb.svn.sourceforge.net/svnroot/rdwtwdb rdwtwdb
you might try building with -Wl,--export-dynamic linker argument. I recall needing this argument when encountering similar behavior.
3,237,247
3,237,293
C++ Rounding to the _nths place
I'm currently learning c++ on a linux machine. I've got the following code for rounding down or up accordingly but only whole numbers. How would I change this code to round to the hundredths place or any other decimal? I wouldn't ask if I didn't try looking everywhere already :( and some answers seem to have a ton of lines for what seems to be a simple function! double round( double ){ return floor(value + 0.5 ); }
Try double round( double value ) { return floor( value*100 + 0.5 )/100; } to round to two decimal places.
3,237,534
7,712,880
pthread_mutex_lock and unlock
i have two threads, they run pretty fast, i'm using pthread_mutex_lock and pthread_mutex_unlock to access global (externed variables) data the problem is that my application takes about 15-20% of CPU running on Ubuntu Linux, the same code but with EnterCriticalSection and LeaveCriticalSection and running on Windows uses 1-2% of CPU
found the fastest way, just use pthread rwlocks!
3,237,594
3,237,612
Unused friend class in C++
Is there a way to detect (for instance with compiler warning) if classes are declared friend but do not access private members, ie. when friendship is useless?
Compiler warnings are not standardised, so this depends on your specific compiler(s). I would be very surprised if any of them supported this, however. A similar situation would be if you had a public member function which was only called by other public members (meaning it needn't be public), and once again I don't think any compilers detect this. Doing either of these tests would mean extra work for the compiler writers, and I doubt if they would see them as sufficiently useful to implement.
3,237,642
3,238,060
What to do with "This application has failed to start because myproject.dll was not found." error
I have a project A linked to a project B. B is compiled into a .dll while A is the main program and compiled into a .exe The compiling of the projects is done without any issues, but when I run the program, I get a pop-up window saying "This application has failed to start because B.dll was not found. Re-installing the application may solve the problem." I have done several cleanings, tried to move the dll, but that won't work. I am using visual Studio 9.0 btw
When Windows loads an EXE, it will check what DLL's are needed, directly or indirectly. In your case, A.EXE will need B.dll. When Windows has determined that list, it will use this procedure to locate the DLLs: The directory where the executable is stored [1] The current directory, as set by CreateProcess() The Windows system directory (holds most of the Windows DLLs such as USER32.DLL) The Windows directory (for legacy reasons, mostly) The directories from the PATH variable (also for legacy reasons) [1] Symbolic links can cause an executable to have multiple paths. To be precise here, it's the path of the executable that was passed to CreateProcess.
3,237,689
3,237,731
where is the hid.lib file in windows?
I'm doing some HiD programming and I'm trying to locate HiD.lib file to add to my .pro Qt file. However I can't find it. Below is an excerpt of said file: win32:LIBS+=-lSetupAPI.lib -L"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib" \ -lKernel32.lib -L"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib" \ -lHid.lib -L"" #Looking for the relevant path Thanks for your help. edit: Could this library be buried now under something else?
You need the Windows Driver Kit for the hid.lib.
3,238,246
3,238,257
How to use .Net System.IO; System.Net; System.Net.Sockets; from Visual Studio C++ project?
How to use .Net System.IO; System.Net; System.Net.Sockets; libs from Visual Studio C++ project?
Those are managed assemblies, meaning you will have to use C++/CLI. Wikipedia has some pretty good information on that: http://en.wikipedia.org/wiki/C%2B%2B/CLI [edit] Also, of course, there's the MSDN article on C++/CLI: http://msdn.microsoft.com/en-us/library/ms379617(VS.80).aspx
3,238,309
3,238,655
Performance of C++ calls to Java code vs C# code
I am exploring a solution at my client where we have to call an API that is available in both C# and Java from our C++ application. We would like this to be a cross platform application (PC & Mac), so Java is preferred, but performance is more important. I've been trying to do some research on the performance of C++ calls to C# vs Java but haven't found any solid information. The idea is to use JNI to call the Java API or managed C++ to call the C# API. Does anyone out there have information or insight as to what would be better performance wise? These calls will potentially be performed heavily, so volume does come into play. Thanks!
I cannot offer you a definitive answer, but I have done JNI to C library calls (not the reverse), .NET to wrapped Java library calls, and .NET to .NET library calls. I don't have official numbers on any of them, but the .NET to .NET calls, whether managed C++ or C# were both the easiest and fastest. Because they were both .NET, there was a common set of datatypes supported on both sides. In the other instances, there was lots of ugly marshaling code required to convert between datatypes in different languages. The .NET Framework was designed with the intent that calls between different .NET libraries would be transparent of their original language and it does this very well. Another consideration is that in a high-volume environment, the performance of the individual libraries may be a bigger concern than the interop performance. In other words, if the Java library is 25% faster than the C# library, it may make sense to use the Java library even if the interop with C# is faster and easier than with Java.
3,238,329
3,238,418
Class to class conversion using constructor+inheritance in C++
Here I can do conversion from emp class object to emp class object. But I can't do conversion from employee class object to emp class object - I have added comment where I am getting error - 'setEmpID' is not a member of 'employee'. what should I do to resolve this error? (I am just preparing for C++ exam and this is the only one that I couldn't solve). Edit - see this is the definition of program - There are two classes Emp and Employee.Emp is defined in the payroll department containing details about employee id and details about his/her payment. Employee isHuman resource department class containing only basic salary details and full personal details like name of spouse, number of children, previous experience of an employee etc. Add code in the Emp class such that, conversion from one type of employee object into another is possible. While converting, items which are not here in the source class (like No. of children when source class is Employee) should take a default value. #include<iostream.h> #include<conio.h> #include<string.h> class employee; class emp { private: unsigned int empID; public: emp(){ empID=0; } emp(unsigned int x){ empID=x; } emp(employee tmp) { // i am getting error here. tmp.setEmpID(10); } void setEmpID(unsigned int x){ empID=x; } int getEmpID(){ return empID; } }; class employee : public emp { private: char name[30]; public: employee(); employee(unsigned int x); employee(unsigned int x,char y[]); employee(emp tmp); void display(); }; employee :: employee() { emp(); name[0]='\0'; } employee :: employee(unsigned int x) { emp(x); name[0]='\0'; } employee :: employee(unsigned int x,char y[]) : emp(x) { strcpy(name,y); } employee :: employee(emp tmp) : emp( tmp.getEmpID() ) { name[0]='\0'; } void employee :: display(){ cout<<"No is -> "<<getEmpID()<<endl<<"Name -> "<<name; } void main() { clrscr(); emp e1(10); employee e2(10u,"nimita"); cout<<e1.getEmpID()<<endl; e2.display(); getch(); }
At the point of call to tmp.setEmpID(10), the definition of class employee is not yet seen by the compiler, since it was just forward declared. So the compiler has no knowledge of the class' methods yet. In other words this is a cyclical dependency. Luckily it is easy to resolve by moving the implementation of emp(employee tmp) to e.g. the cpp file, where both class definitions are visible.
3,238,344
3,238,414
c++ what is the advantage of lex and bison to a selfmade tokenizer / parser
I would like to do some parsing and tokenizing in c++ for learning purposes. Now I often times came across bison/yacc and lex when reading about this subject online. Would there be any mayor benefit of using those over for instance a tokenizer/parser written using STL or boost::regex or maybe even just C?
I recently undertook writing a simple lexer and parser. It turned out that the lexer was simpler to code by hand. But the parser was a little more difficult. My Bison-generated parser worked almost right off the bat, and it gave me a lot of helpful messages about where I had forgotten about states. I later wrote the same parser by hand but it took a lot more debugging before I had it working perfectly. The appeal of generating tools for lexers and parsers is that you can write the specification in a clean, easy-to-read language that comes close to being a shortest-possible rendition of your spec. A hand-written parser is usually at least twice as big. Also, the automated parser (/lexer) comes with a lot of diagnostic code and logic to help you get the thing debugged. A parser/lexer spec in BNF-like language is also a lot easier to change, should your language or requirements change. If you're dealing with a hand-written parser/lexer, you may need to dig deeply into your code and make significant changes. Finally, because they're often implemented as finite state machines without backtracking (gazillions of options on Bison, so this is not always a given), it's quite possible that your auto-generated code will be more efficient than your hand-coded product.
3,238,351
3,239,358
Is it possible to transate the wParam parameter into the actual message string?
I am trying to get the actual system messages that are represented by the intergers returned in the wParam property of the message. Is there anyway to do this or a function that can achieve this?
Is this is a question about WndProc? Which message are you talking about? LRESULT CALLBACK WndProc(HWND p_hwn,UINT p_msg,WPARAM p_wparam,LPARAM p_lparam) The WParam is generally used to send flags or info attached to a windows message, it doesn't tell you what the message is. The message id (p_msg) tells you what message it is e.g. 'WM_CHAR', 'WM_KEYDOWN' etc? Is it these you are after? If so you can download an enumeration here (C# but easy to convert): http://www.codeproject.com/KB/cs/cswindowsmessages.aspx Or of course just look in the C++ windows headers.
3,238,380
3,238,419
Is increased programming efficiency in Java or C# a myth?
A big advantage of Java or C# in increasing productivity of development is that you're supposed to lose less time with complicated language features, especially those related to memory management. But is it just an impression? I think that the learning curve for C++ is definitely more steep, but for a proficient C++ programmer, and given a set of coding standards for C++, isn't the difference between Java and C++ fading away?
for a proficient C++ programmer This is the problem. In my experience, most programmers are NOT proficient. Java allows mindless assembly line workers to be productive in a way that C++ does not. Proficient developers will be productive no matter what language they write with.
3,238,420
3,238,802
Outputting a vector of string objects to a file
I'm trying to output a vector of string objects to a file. However, my code only outputs the first two elements of each string. The piece of code below writes: 1 1 to a file. Rather then: 01-Jul-09 01-Jul-10 which is what I need. ofstream file("dates.out"); vector<string> Test(2); Test[0] = "01-Jul-09"; Test[1] = "01-Jul-10"; for(unsigned int i=0; i<Test.size(); i++) file << Test[i] << endl; file.close(); Is not clear to me what could be going wrong as I have used string objects before in similar contexts. Any help would be welcome!
As already observed, the code appears fine, so: Are you looking at the right dates.out after your program runs? Did you verify the date/time on the file you're looking at to make sure it isn't previous data? Do you have permission to write to the file? Perhaps your program is failing to overwrite existing data. Did you show us ALL the important code? Are there any other function calls we need to know about? Does the code in Marcelo/ereOn's answers produce the same problem as in your question? Are you sure that you're running the binary you think you are? (PATH issues possibly).
3,238,718
3,238,730
Difference between const variable and const type variable
What is the difference between: const variable = 10; and const int variable = 10; Does variable, per the standard, get interpreted as an integral type when no type is defined?
const variable = 10 is not valid C++, while const int variable = 10; is. The only time (that I can think of) that const variable = 10 would be valid is if you had a type named variable and you had a function with an unnamed parameter of that type, taking a default argument: typedef int variable; void foo(const variable = 10);
3,238,832
3,238,882
How to get the return type of a boost::signal?
I use boost::signal with different function signatures and different combiners. In a class that looks like the one beyond I want to get the return of a certain signal declaration. template<typename signal_type> class MyClass { signal_type mSignal; signal_type::result_type getResult() { return mSignal(); } } But signal_type::result_type does not work. So is there a way to get the return type?
You need typename to use dependent types: typename signal_type::result_type getResult() { return mSignal(); } Dependent names (i.e. dependent on a template parameter) are assumed to not name types unless prefixed with typename and to not name templates unless immediately prefixed with template.
3,238,952
3,238,993
Can you force unreferenced code to be linked in from a static library?
Here's the scenario - I have created a custom NSView subclass, and the implementation is in a static library. The class is never referenced from the final executable, only from the Interface Builder XML file. Since it's not referenced, it doesn't get included at link time, and as a result the class can't be found at runtime. Is there any way to force it to be linked in, other thank link dynamically or compile the class directly into the executable itself?
You can use the class class method on it, which will mostly be a no-op, but will reference it from your code. int main(int argc, const char** argv) { [MyClass class]; // There you are! MyClass is now referenced from your code. /* ... rest of your main function ... */ }
3,239,090
3,311,159
How you use technique (described) to work with C structures and pointers from .Net?
How you use technique described here to work with C structures from .Net? Ofcourse I need a code example - on 3 parts: C declaring parts, C++ wrapping around C and C# acsessing. So what I wonder Is C structture A has as one of its params structure B which consists of at least 2 types one of which is pointer to some variable C which should be declared. We whant to have access from C# .Net to all A and B structures and its params and that variable C. How to do such thing?
Suppose these are the C structs in a file named structs.h struct StructB { int bMember1; int bMember2; int* bMember3; }; struct StructA { struct StructB aMember1; }; In a new VC++ DLL project, enable Common Language RunTime Support (Old Syntax) and make sure C++ Exceptions are disabled. Build this for release target. extern "C" { #include "structs.h" } namespace Wrapper { public __gc class NewStructB { private: StructB b; public: NewStructB() { } ~NewStructB() { } int getBMember1() { return b.bMember1; } void setBMember1(int value) { b.bMember1 = value; } int getBMember2() { return b.bMember2; } void setBMember2(int value) { b.bMember2 = value; } int* getBMember3() { return b.bMember3; } void setBMember3(int* value) { b.bMember3 = value; } }; public __gc class NewStructA { public: NewStructB* b; NewStructA() { b = new NewStructB(); } ~NewStructA() { delete b; } void ShowInfo() { System::Console::WriteLine(b->getBMember1().ToString()); System::Console::WriteLine(b->getBMember2().ToString()); System::Console::WriteLine((*b->getBMember3()).ToString()); } }; }; Then create a new C# Console Application and reference the .dll file we just built. In Project Properties > Build, check "Allow unsafe code". static void Main(string[] args) { int toBePointed = 12345; Wrapper.NewStructA a = new Wrapper.NewStructA(); a.b.setBMember1(10); a.b.setBMember2(20); unsafe { a.b.setBMember3(&toBePointed); } a.ShowInfo(); Console.ReadKey(); } As you can see, the original StructA is in a way eliminated!! And I'm not aware of any other way to access C structure members directly from C# due to access issues.
3,239,473
3,239,548
C++: Cast to an interface that is not part of the base class
I have a series of classes representing "smart" map elements: MapTextElement, MapIconElement, etc. The classes are extending various Qt graphics item classes, but also provide common functionality, such as an abstract factory method that returns a property panel specialized for each class. I have declared these common methods in a pure virtual class, MapElementInterface. My classes then multiply-inherit the appropriate Qt base class as well as the interface: class MapTextElement : public QGraphicsTextItem, public MapElementInterface class MapIconElement : public QGraphicsItem, public MapElementInterface So my class hierarchy looks kind of like: +-------------+ +-------------------+ |QGraphicsItem| |MapElementInterface| +-------------+ +-------------------+ ^ ^ ^ | | | +------+------+ | | | | | | +-----------------+ +--------------+ | |QGraphicsTextItem| |MapIconElement| | +-----------------+ +--------------+ | ^ | | | +-------------------+ +-----+ | | +--------------+ |MapTextElement| +--------------+ I am receiving a pointer to a QGraphicsItem from a Qt-provided method. In this case, I know that the pointer is not only QGraphicsItem, but also MapElementInterface. I want to treat the pointer as a MapElementInterface. QList<QGraphicsItem*> selected = scene_->selectedItems(); if (selected.count() == 1) { // We know that the selected item implements MapEditorInterface MapElementInterface *element = SOME_CAST_HERE<MapElementInterface*>(selected[0]); QWidget *panel = element->GeneratePropertyPanel(property_dock_); } What is the proper cast to use? Or am I going about this completely the wrong way?
With multiple inheritance, dynamic_cast is the only way, and check the return value against NULL.
3,239,504
3,239,593
Event filter on QGraphicsItem
Is it possible to have an event filter on a QGraphicsItem? Eventfilter has a param that gives you a QObject, but since QGraphicsItem isn't derived from QObject, then how would it work?
Edit: Use QGraphicsItem::installSceneEventFilter as suggested in @Frank's answer. Example: QGraphicsScene scene; QGraphicsEllipseItem *ellipse = scene.addEllipse(QRectF(-10, -10, 20, 20)); QGraphicsLineItem *line = scene.addLine(QLineF(-10, -10, 20, 20)); line->installSceneEventFilter(ellipse); // line's events are filtered by ellipse's sceneEventFilter() function. ellipse->installSceneEventFilter(line); // ellipse's events are filtered by line's sceneEventFilter() function. The first thing that popped into my mind was this: Create a new class, derived from both QGraphicsItem and QObject, since these are unrelated (as far as a glance at the docs tells me), you should have what you wanted. .... But then I looked at the docs more closely and found QGraphicsObject, which is probably exactly what you want, it even already has the member eventFilter
3,239,546
3,239,717
C++ Game State System
Okay: I'm fairly new to C++ and static languages on a whole. Coming from years of ruby (and other dynamic languages) I don't know if this is possible. I've been making a game state system for... well a game. I want to make the system easy for me to cut and paste into other games without any (or very few) changes. The two things I am wanting to improve are the way in which states switch and the way in which state pointers are held. There could be any number of states, but there will always be at least 2 to 3 states active in memory. Ugliness No 1. Currently I have a state manager class with something like this in it: void StateManager::changeState(StateID nextStateID) { // UNFOCUS THE CURRENT STATE // if (currentState()) { currentState()->onUnFocus(); // DESTROY THE STATE IF IT WANTS IT // if(currentState()->isDestroyedOnUnFocus()) { destroyCurrentState(); } } if (m_GameStates[nextStateID]) { // SWITCH TO NEXT STATE // setCurrentState(nextStateID); } else { // CREATE NEW STATE // switch (nextStateID) { case MainMenuStateID: m_GameStates[MainMenuStateID] = new MainMenuState; break; case GameStateID: m_GameStates[MainMenuStateID] = new GameStates; break; }; setCurrentState(nextStateID); } // FOCUS NEXT STATE // currentState()->onFocus(); } This approach works but I don't feel it's very nice. Is it possible to pass a type? And then call new on it? new NextGameState; // Whatever type that may be. Can poloymophism help here? All States are derived from a class State. Ugliness No 2. Another thing I think needs some improvement is the way I've been storing the states. State* m_GameStates[MaxNumberOfStates]; All the states are initialized to NULL, so I can test if a state is there, and if not it creates one when needed. It works well as I can call the current state: m_GameStates[m_CurrentState]; However, I don't like this for two reasons. It seems a bit of a waste having an array full of NULL pointers when there will only be 2 or 3 pointers active at any one time. [Editor's note: what is the second reason?] I thought about shifting this into a vector_ptr, but didn't as it would create extra complications with checking to see if a state exists. And the vector seems to reinforce Ugliness No 1. as I need to have a list to check each state. Any advice or direction appreciated. Thanks, Phil.
For your first problem, yes, you can pass in a type, with some caveats. I've added a comment under your question, asking for a bit more information. Until we get that, I can't really say how it should be done, but read up on templates. You can make a function template, which can be passed a type, for example like this: template <typename T> void Foo() { T* x = new T(); ... } Foo<int>() // call Foo with the type T set to 'int' There are some limitations to this, as the types have to be specified at compile-time, but it is a very powerful language feature. Another option, which might work better since you seem to have an association between a variable (MainState) and a type (MainMenu), might be the use of traits classes. Again, I'm unsure of exactly how it'd be done in your case, since we haven't seen the entirety of the function (in particular, what type is MainState, and how/when is it created?) It might also be possible to solve the problem through polymorphism, but again, I'd need to see a bit more of the context to suggest a solution. For your second problem, you can use the standard library map: #include <map> // I'm not sure what type m_CurrentState is, so use its type instead of KeyType below std::map<KeyType, State*> m_GameStates; // and to perform a lookup in the map: GameStates[m_CurrentState]; Finally, a really really important bit of advice: Stop using pointers everywhere. Stop calling new to create new objects. As a general rule, objects should be created on the stack (Instead of Foo* f = new Foo;, just do Foo f; And instead of using pointers, you'll often want to just copy the object itself. Alternatively, create references instead of pointers. And when you do need to use dynamic memory allocations, you still shouldn't use new directly. Instead, create a wrapper object, which internally allocates what it needs with new in its constructor, and frees it again in the destructor. If you do this correctly, it pretty much solves all the headaches of memory management. The general technique is called RAII.
3,239,744
3,295,472
Setting item height of a list view? (using custom draw)
How can I set the row height of a custom drawn list view? Or does it require an owner drawn list view?
It depends on the mode you are using it in. In some modes, you can use the LVM_SETITEMHEIGHT message. In others some modes, the item height is dictated by the height of an associated ImageList, if any, followed by the height of the assigned Font. Update: turns out that LVM_SETITEMHEIGHT is part of the MiniGUI library, not part of the Win32 API. In that case, you would have to use the LVS_OWNERDRAWFIXED window style and then subclass the ListView to handle the WM_MEASUREITEM message.
3,239,905
3,239,934
C++ mutex and const correctness
Is there convention regarding whenever method which is essentially read-only, but has mutex/ lock which may need to be modified, is const or not? if there is not one, what would be disadvantage/bad design if such method is const Thank you
You can mark data members with the keyword mutable to allow them to be modified in a constant member function, e.g.: struct foo { mutable mutex foo_mutex; // .... void bar() const { auto_locker lock(foo_mutex); // ... } }; Try to do this as little as possible because abusing mutable is evil.
3,239,968
3,240,014
Detecting precision loss when converting from double to float
I am writing a piece of code in which i have to convert from double to float values. I am using boost::numeric_cast to do this conversion which will alert me of any overflow/underflow. However i am also interested in knowing if that conversion resulted in some precision loss or not. For example double source = 1988.1012; float dest = numeric_cast<float>(source); Produces dest which has value 1988.1 Is there any way available in which i can detect this kind of precision loss/rounding
You could cast the float back to a double and compare this double to the original - that should give you a fair indication as to whether there was a loss of precision.
3,240,005
3,240,174
Design problem relating to manipulating unknown types
I am stuck with a design problem that I hope you guys can help with. I have a few different classes that have various parameters (more than 20 in each case, and they are mostly different, although some are exactly the same in which case they inherit from a base class). I want to control these parameters through the user of a class called ObjectProperties. Each class will create ObjectProperties and populate it with it's own parameter list when the class is initialized. This is done with a map which is set up like so: std::map<std::string, [data_type]> // where [data_type] can be an int, float, bool, string etc. the 'string' is the name for the parameter and the data type is the type it's associated with. This is done for easy scripting later on (instead of having 20+ getters/setters). I have already made the ObjectProperties class, but it is less than ideal. I have a structure with all the possible data types called DataTypeStruct and a variable for the map in the ObjectProperties class called pDataTypeMap; typedef struct { int* IntValue; float* FloatValue; bool* BoolValue; std::string* StringValue; }DataTypeStruct; std::map<std::string, DataTypeStruct> pDataTypeMap; When a class wants to add a parameter for manipulation, it calls one of the following functions, which then creates a new structure appropriately and pairs it with the name to be put in the map. The function returns true or false depending on whether it was able to insert it or not (if false, then the name already exists) bool AddParam(std::string aName, int* aParam); bool AddParam(std::string aName, float* aParam); bool AddParam(std::string aName, bool* aParam); bool AddParam(std::string aName, std::string* aString); The reason aParam is/are pointers is because it is required that the parameters must be passed by reference so that they can be manipulated later on. To change the value for the parameter I have similar functions. As you can see, this is less than ideal, as I have wasted some space with the structure (where each new structure only stores an int OR a bool OR a string OR a float), and calling overloaded functions is unsafe (I 'can' make the functions have unique names, but again, that is less than ideal). I hope I have explained the design issue that I have come across (it is a little difficult to explain) and would really like to hear suggestions on how to go about solving this problem.
I would suggest first taking a look at boost::any, boost:variant, boost::tuple or boost::fusion::vector as the 'vehicles' for your [data_type].
3,240,082
3,240,898
OnRButtonDown on a modal dialog
I have a modal dialog that I would like to implement a right mouse click event on. I have added ON_WM_RBUTTONDOWN() to the class's message map. BEGIN_MESSAGE_MAP(MyDialog, CDialog) //{{AFX_MSG_MAP(MyDialog) ON_WM_RBUTTONDOWN() //}}AFX_MSG_MAP END_MESSAGE_MAP() and have overridden the class's afx_msg void OnRButtonDown(UINT nFlags, CPoint point); However, my OnRButtonDown function does not execute when I click the mouse button on the Dialog window. My dialog is called using DoModal(), could it be that modal dialogs don't allow for these mouse events? Is there something else that I'm missing?
No, this should work also in modal dialogs. Two possible scenarios: you have an invisible control which captures the click you have overridden the window procedure and do something unwanted with the message.
3,240,241
3,242,884
Recommended practices for re-entrant code in C, C++
I was going through a re-entrancy guide on recommended practices when writing re-entrant code. What other references and resources cover this topic? What lint-like tools can be used to check for these issues?
The guide is sufficient. My personal rule of thumbs are only 2 for re-reentering code: take only pass by value parameters, used only value passed in as parameters in the function. if I need to use any global parameters or pointer (for performance or storage sake), use a mutex or semaphore to control access to it.
3,240,263
3,248,175
Sharing an enum from C#, C++/CLI, and C++
I have a library that consists of three parts. First is native C++, which provides the actual functionality. Second is a C++/CLI wrapper/adaptor for the C++ library, to simplify the C# to C++ transition. Finally I have a C# library, which invokes the C++ library through the C++/CLI adaptor. Right now there I have two sets of parallel enum definitions, one stored in a .cs file and the other in a .h file. This poses a double problem: I have dual maintenance. I must always synchronize changes of an enum in both file locations. The namespace used by both enums should be identical but the C++/CLI wrapper, which views both sets of enums and translates between them, incurs a naming collision. Right now I'm not sure a solution such as this or that would solve both problems. Thoughts?
Just put your #include "Enum.cs" directive inside an outer namespace to resolve the naming collision. EDIT: A variation suggested by Brent is to use #define to substitute one of the namespaces (or even the enum name itself) declared in the .cs file. This also avoids the naming collision, without making the namespace hierarchy deeper.