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
947,394
947,425
What is the point of make_heap?
Can someone please tell me the point of the STL heap function templates like std::make_heap? Why would anyone ever use them? Is there a practical use?
If you want to make a priority queue out from a list, well, you can use make_heap: Internally, a heap is a tree where each node links to values not greater than its own value. In heaps generated by make_heap, the specific position of an element in the tree rather than being determined by memory-consuming links is determined by its absolute position in the sequence, with *first being always the highest value in the heap. Heaps allow to add or remove elements from it in logarithmic time by using functions push_heap and pop_heap, which preserve its heap properties.
947,489
947,541
Does a standard implementation of a Circular List exist for C++?
I want to use a circular list. Short of implementing my own (like this person did) what are my options? Specifically what I want to do is iterate over a list of objects. When my iterator reaches the end of the list, it should automatically return to the beginning. (Yes, I realize this could be dangerous.) See Vladimir's definition of a circular_iterator: "A circular_iterator will never be equal with CircularList::end(), thus you can always dereference this iterator."
There's no standard circular list. However, there is a circular buffer in Boost, which might be helpful. If you don't need anything fancy, you might consider just using a vector and accessing the elements with an index. You can just mod your index with the size of the vector to achieve much the same thing as a circular list.
947,621
947,636
How do I convert a long to a string in C++?
How do I convert a long to a string in C++?
You could use stringstream. #include <sstream> // ... std::string number; std::stringstream strstream; strstream << 1L; strstream >> number; There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though. The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.
947,742
947,755
debug command line application
I'm wondering if it's possible to debug a command line application (where main received arguments argc, and **argv) in visual studio 2008?
You can easily set the command arguments to the executable from within Visual Studio, in the Debugging screen under Configuration Properties (at least that's where it is in 2005).
947,802
947,939
Lua / c++ problem handling named array entries
I'm trying to write some c++ classes for interfacing with LUA and I am confused about the following: In the following example: Wherigo.ZCommand returns a "Command" objects, also zcharacterFisherman.Commands is an array of Command objects: With the following LUA code, I understand it and it works by properly (luaL_getn returns 3 in the zcharacterFisherman.Commands c++ set newindex function): zcharacterFisherman.Commands = { Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"}, Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"}, Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"}, } But when the array is defined with the following LUA code with a slightly different syntax luaL_getn returns 0. zcharacterFisherman.Commands = { Talk = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"}, Talk2 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"}, Talk3 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"}, } All objects are defined in c++ and the c++ objects hold all the object members so I am trying to just connect LUA to those c++ objects. Is this enough or do I need to post some of my code??
luaL_getn is for getting the highest numeric element of an array in Lua. An array is a table with only integer indices. When you define a table in Lua (the first example) without explicitly setting indices, you will get an array with elements 1, 2, and 3. Naturally, luaL_getn returns a 3 here. luaL_getn is NOT defined to return the number of elements in the table, it is defined to return the highest numeric index in the table (see http://www.lua.org/manual/5.1/manual.html#pdf-table.maxn) The second example is NOT using numeric indices, and this table is not a Lua array -- it is more like a hash table. Since luaL_getn only works on true arrays, you wouldn't expect it to work here. Unfortunately, there is no simple way to get the number of elements in a table (lua_objlen solves a related problem, but does not fix this one). The only way to do it is to either: Always use array notation. Don't ever use anything else as the keys in your table. You will get a lot of speed-ups this way. Iterate through your table and count the number of elements when you wish to know the table's size. The language does not provide a one-line method for getting the size of a full table, since general tables are implemented using hashes and do not track their element count.
947,864
947,887
debug assertion error
I've been scratching my head for quite some time now, this code worked fine when I first used cmd to go inside the project\debug folder then run the program there. Then I added the if(in) and else part then it started giving me "debug assertion failed" errors mbstowcs.c Expression s != NULL It just doesn't make any sense to me.. I used this command in cmd: prog.exe test.txt nuther.txt Both files exists inside the debug folder and the main project folder.. Any ideas? int main(int argc, char **argv) { parse_opts(argc, argv); //parse the arguments return 0; } void parse_opts(int argc, char **argv) { string compl_out; if( argc > 1 ) { for( int i = 1; i < argc; i++ ) { if( argv[i][0] = '>' ) { ofstream out_file(argv[i+1]); out_file << compl_out; out_file.close(); break; } ifstream in(argv[i]); string buff; if(in) { while(getline( in, buff )) cout << buff << endl; compl_out.append(buff); } else { cout << "Can't open file: " << argv[i] << ", file doesn't exist or is locked in use. " << endl; } } } else { usage(); } }
First impressions: if( argv[i][0] = '>' ) should be: if( argv[i][0] == '>' ) You are assigning instead of comparing. I think you also might have intended the compl_out.append to be inside the while loop? As it is it won't append anying to that buffer: while(getline( in, buff )) { cout << "buf" << buff << endl; compl_out.append(buff); }
947,943
947,970
Template specialisation where templated type is also a template
I've created a small utility function for string conversion so that I don't have to go around creating ostringstream objects all over the place template<typename T> inline string ToString(const T& x) { std::ostringstream o; if (!(o << x)) throw BadConversion(string("ToString(") + typeid(x).name() + ")"); return o.str(); } I want to provide some specialisations of this method for instances where there is no default overloaded << operator for stringstream (i.e. std::pair, std::set, my own classes) and I've run into difficulties with the templating. I will illustrate with the std::pair example, if I want to be able to string str = ToString(make_pair(3, 4)); the only way I can think of to do it is to define the explicit specialisation for int template<> inline string ToString(const pair<int,int>& x) { std::ostringstream o; if (!(o << "[" << x.first << "," << x.second << "]")) throw BadConversion(string("ToString(pair<int,int>)")); return o.str(); } is there a way I can define this for the generic case? template<> inline string ToString(const pair<T1,T2>& x) { std::ostringstream o; if (!(o << "[" << x.first << "," << x.second << "]")) throw BadConversion(string("ToString(pair<T1,T2>)")); return o.str(); }
Don't specialize the template, but overload it. The compiler will figure out what function template to take by ordering them according to their specialization of their function parameter types (this is called partial ordering). template<typename T1, typename T2> inline string ToString(const std::pair<T1, T2>& x) { std::ostringstream o; if (!(o << "[" << x.first << "," << x.second << "]")) throw BadConversion(string("ToString(pair<T1,T2>)")); return o.str(); } In general, partial ordering will result in exactly what you expect. In more detail, consider having these two functions template<typename T> void f(T); template<typename T, typename U> void f(pair<T, U>); Now, to see whether one is at least as specialized as the other one, we test the following for both function templates: chose some unique type for each template parameter, substitute that into the function parameter list. With that parameter list as argument, make argument deduction on the other template (make a virtual call with those arguments to that other template). If the deduction succeeds and there is no conversion required (adding const is such one). Example for the above: substituting some type X1 into T gives us some type, call it X1. argument deduction of X1 against pair<T, U> won't work. So the first is not at least as specialized as the second template. substituting types Y1 and Y2 into pair<T, U> yields pair<Y1, Y2>. Doing argument deduction against T of the first template works: T will be deduced as pair<Y1, Y2>. So the second is at least as specialized as the first. The rule is, a function template A is more specialized than the other B, if A is at least as specialized as B, but B is not at least as specialized as A. So, the second wins in our example: It's more specialized, and it will be chosen if we could in principle call both template functions. I'm afraid, that overview was in a hurry, i only did it for type parameters and skipped some details. Look into 14.5.5.2 in the C++ Standard Spec to see the gory details. g
948,947
949,262
What are the differences between parameter definitions as (type& name), and (type* name)?
A very basic question, but still, it would be good to hear from C++ gurus out there. There are two rather similar ways to declare by-reference parameters in C++. 1) Using "asterisk": void DoOne(std::wstring* iData); 2) Using "ampersand": void DoTwo(std::wstring& iData); What are implications of each method? Are there any gotcha's in any case? Bonus #1: What would be a formal way to call method in #1 and #2? Are they both called "by-reference"? Bonus #2: std::wstring is used deliberately. What would be implications towards standard library classes in each case?
#1 uses a pointer parameter ('passing a pointer to'), #2 uses a reference parameter ('passing by reference'). They are very similar, but note that the calling code looks different in the two cases: std::wstring s; DoOne(&s); // pass a pointer to s DoTwo(s); // pass s by reference Some people prefer #1, using a convention that passing by pointer indicates that the function might change the value of s (even though either function could). Other people (myself included) prefer #2, since passing by reference does not allow NULL to be passed. There is another important difference when passing by const pointer or reference. A temporary variable can only be passed to a const reference parameter: void ByConstPointer(const std::wstring&); void ByConstReference(const std::wstring*); void test() { ByConstPointer(&std::wstring(L"Hello")); // error: cannot take address of temporary ByConstReference(std::wstring(L"Hello")); // fine }
949,045
949,055
What is the importance of returning reference in operator overloading
Can anybody explain why do you need to return a reference while overloading operators e.g. friend std::ostream& operator<< (std::ostream& out, const std::string& str)
It is to make "chaining" of the operator work, in examples like this: std::cout << "hello," << " world"; If the first (leftmost) use of the operator<<() hadn't returned a reference, there would not be an object to call for the second use of the operator.
949,064
949,093
Cheating in online games: Is it possible to prevent one Win32 process from inspecting/manipulating another's memory?
I play the online game World of Warcraft, which is plagued by automated bots that inspect the game's allocated memory in order to read game/player/world state information, which is used to mechanically play the game. They also sometimes write directly to the game's memory itself but the more sophisticated ones don't, as far as I know. The game's vendor, Blizzard Entertainment, has a separate application called Warden that it is supposed to detect and disable hacks and cheats like that, but it doesn't catch everything. Would it be possible to make a Windows application where you're the only one that can read the things you've read into memory? Would that be pragmatic to implement on a large C++ application that runs on millions of machines?
Can't be done. The application is at the mercy of the OS when it comes to memory access. Whoever controls the OS controls access to memory. A user has full access to the whole machine, so they can always starts processes with privileges set to allow them to read from other processes' memory space. This is assuming a 'regular' environment - today's hardware, with a multipurpose OS that allows several simultaneous programs to run, etc. Think of it this way - even single-purpose machines where developers have full control over the hardware, with digital signing and all the tricks possible like the XBox or PlayStation can't manage to keep third-party code out. For a multi-purpose OS, it'd be 10 times harder.
949,222
949,670
Adding some custom data to the Qt tree model
I am a noob in using model/view paradigm in Qt and have the following problem: I have a tree-like structure, that must be visualized via Qt. I found out, that QAbstractTableModel is perfect for my needs, so I write the following: class columnViewModel : public QAbstractTableModel { // some stuff... }; Everything now works, but now I have to implement an "Observer" design pattern over the nodes of my tree. Whenever the node expands in the TreeView, I must add an Observer to the corresponding node. Whenever the node collapses, I must remove this Observer from the node. So, I write something, like this: void onExpand( const QModelIndex & Index ... ) { Node* myNode = static_cast<Node*>(Index->internalPointer()); Observer* foo = Observer::create(); myNode->addObserver(foo); // ok up to here, but now where can I save this Observer? I must associate // it with the Node, but I cannot change the Node class. Is there any way // to save it within the index? } void onCollapse( const QModelIndex & Index ... ) { Node* myNode = static_cast<Node*>Index->internalPointer(); Observer* foo = // well, what should I write here? Node does not have anything // like "getObserver()"! Can I extract an Observer from Index? myNode->remObserver( foo ); } I don't have the snippets right now, so the code may be not a valid Qt, but the problem seems clear. I can change neither Node nor Observer classes. I can have a inner list of Observers, but then I have to resolve, what Observer to remove from the specific node. Is there any way to save the Observer pointer within Index (some user data maybe), to resolve it quickly in onCollapse? Any ideas would be welcome...
Do the following: Define a new role (similar to Qt::UserRole), let's say ObserverRole. Use QAbstractItemModel::setData to set the observer as data with observer role. The code sketch: this->model()->setData( ObserverRole, QVariant::fromValue( foo)); You might need to put in the cpp implementation file a declaration for metadata, something like Q__DECLARE __METATYPE ( Observer* ); to allow QVariant to make the variant casts in a proper way. You can get the observer for an index using QModelIndex::data with Observer role: index.data( ObserverRole); In your model implementation, add support for returning data for Observer role, if any (as you probably did for Qt::UserRole or Qt::DisplayRole. Update on received comment: Normally, the QModelIndex::data gives the data for the viewer. The role specified when asking for data allows the customizer of the model to provide different data for different reasons (e.g. provide a string for display role -> the title of the item). If you don't use this mechanism for getting the data, then you probably don't need QTreeView. In this case, use QTreeWidget, where you can work directly with QTreeWidgetItems and to attach data to the item through setData method, or to subclass QTreeWidgetItem and add the data as member of that subclass. The views are usually used when you want to work with models.
949,403
949,456
The specified module could not be found - 64 bit dll
I had the 32 bit dll which is written using Native C, when I tried compiling with VC++(VS2008) for converting the dll to x64 by changing the platform it compiled. But when I tried to access the dll from my C# application which is also 'x64' platform it fails to load the dll. I used Dllimport for linking the dll with my application. The operating system I use in Vista, But I couldnt able to call the at dll function from my application it says failed to load the dll. Is there any way to resolve this issue. Looking forward from your help. Regards, Ga
try the tool "dependency walker" (ldd-like tool for win, www.dependencywalker.com) to find out what links against what. might be helpful.
949,422
949,525
How much memory was actually allocated from heap for an object?
I have a program that uses way too much memory for allocating numerous small objects on heap. So I would like to investigate into ways to optimize it. The program is compiled with Visual C++ 7. Is there a way to determine how much memory is actually allocated for a given object? I mean when I call new the heap allocates not less than the necessary amount. How can I find how much exactly has been allocated?
There is no exact answer, because some heap managers may use different amount of memory for sequential allocations of the same size. Also, there is (usually) no direct way to measure number of bytes the particular allocation took. You can approximate this value by allocating a certain number of items of the same size (say, 4096) and noting the difference in memory used. Dividing the later by the former would give you the answer. Please note that this value changes from OS to OS, and from OS version to OS version and sometimes Debug builds of your application may enable extra heap tracking, which increases the overhead. On some OSes users can change heap policies (i.e. use one heap allocator vs. another as default). Example: Windows and pageheap.exe Just FYI, the default (not LFH) heap on Windows 32-bit takes up: sizeof(your_type), rounded up to DWORD boundary, 3 pointers for prev/next/size 2 pointers for security cookies
949,430
949,895
Does custom action dll-s for msi installer have to be created with Visual Studio only?
I have created setup project with Visual Studio. I also need some custom actions - created DLL with Visual c++ and it works just fine but i don't want to include visual c++ runtime files to my project. So is it possible to build this dll with some other c++ compiler? I have tried to make make it with Dev-c++ but when compiling i get few hundred compilation errors from files msi.h and msiquery.h
Probably the easiest solution is to link your DLLs against the static runtime lib.
949,770
954,501
Is the size of an object needed for creating object on heap?
When compiler need to know the size of a C (class) object: For example, when allocating a C on the stack or as a directly-held member of another type From C++ Coding Standards: 101 Rules, Guidelines, and Best Practices Does that mean for a heap allocated object, size is not necessary? Class C;//just forward declaration C * objc = new C();
To answer your specific question: Does that mean for heap allocated object size is not necessary? Class C;//just forward declaration C * objc = new C(); C++ will not let you do that. Even if it could let you perform a 'new' on an incomplete type by magically resolving the size at a later time (I could envision this being technically possible with cooperation from the linker), the attempt will fail at compile time because of at least 2 reasons: operator new can only be used with complete types. From the C++98 standard 5.3.4 - "[the allocated] type shall be a complete object type, but not an abstract class type or array thereof" the compiler has no idea what constructors exist (and are accessible), so it would also have to fail for that reason.
949,890
951,151
How can I perform pre-main initialization in C/C++ with avr-gcc?
In order to ensure that some initialization code runs before main (using Arduino/avr-gcc) I have code such as the following: class Init { public: Init() { initialize(); } }; Init init; Ideally I'd like to be able to simply write: initialize(); but this doesn't compile... Is there a less verbose way to achieve the same effect? Note: the code is part of an Arduino sketch so the main function is automatically generated and cannot be modified (for example to call initialize before any other code). Update: ideally the initialization would be performed in the setup function, but in this case there is other code depending on it which occurs before main.
You can use GCC's constructor attribute to ensure that it gets called before main(): void Init(void) __attribute__((constructor)); void Init(void) { /* code */ } // This will always run before main()
949,937
951,164
WIN32 memory issue (differences between debug/release)
I'm currently working on a legacy app (win32, Visual C++ 2005) that allocates memory using LocalAlloc (in a supplied library I can't change). The app keeps very large state in fixed memory (created at the start with multiple calls to LocalAlloc( LPTR, size)). I notice that in release mode I run out of memory at about 1.8gb but in debug it happily goes on to over 3.8gb. I'm running XP64 with the /3gb switch. I need to increase the memory used in the app and I'm hitting the memory limit in release (debug works ok). Any ideas?
You probably have the Debug configuration linking with /LARGEADDRESSAWARE and the Release configuration linking with /LARGEADDRESSAWARE:NO (or missing altogether). Check Linker->System->Enable Large Addresses in the project's configuration properties.
949,966
950,015
Creating dynamically loaded Linux libraries using Eclipse
I am writing a program in C++ using Eclipse. I want to compile it as a library for Linux, somthing like a DLL in Windows. How I can do this? Do you know any tutorials on how libraries are created? I just want to understand that is the analog of a DLL for Linux and how to create it. I will be thankful for a small example.
In Linux, DLL's equivalents are (kind of anyway) shared objects (.so). You need to do something like this: $ g++ -c -fPIC libfile1.cpp $ g++ -c -fPIC libfile2.cpp $ g++ -shared -o libyourlib.so libfile1.o libfile2.o Take a look at some open source C++ library projects for more information. GTKMM is one of them. Of course, instead of compiling everything manually it's highly recommended to use a make file or an IDE (such as Eclipse with CDT or KDevelop or {pick your favorite here}) that will create one for you behind the scenes.
950,072
950,106
How reliable is file sharing on Windows when using it for a database?
We have an application that produces a database on disk. The database is made of thousand of files. The application can have from 500 to 3000 file's handle opened at the same time. These handle are kept opened and data is continuously written to. Up until now, it worked really well on local hard drive, but when trying to put the database on a shared disk, we encountered a lot of problems. Is it simply a bad idea or it can work if we change the design of the database engine to open/close file handle on demand? EDIT At this time, we only have one client "connected" to the database.
Based on experience with "shared file" databases (dBase, Paradox and the like) this doesn't scale well. It can also be very sensitive to network errors and bad hardware.
950,130
951,018
Use specific version of vcredist?
Is it possible in Visual Studio 2008 SP1 to target a C++ COM project to vcredist 2008 instead of vcredist 2008 SP1? Our customers have the vcredist 2008 installed and we don't want to force them to install vcredist 2008 SP1. (thousands of computers!)
You can try to remove the embed manifest (look under the project settings Manifest Tool) and provide your own manifest for the application that targets the pre sp1 CRuntime versions. You can also deploy the C-Runtime yourself, in the redist folder under x86/x64 you will find the folder of the C-Runtime (Microsoft.VC90.CRT) just copy those folders in the same folder as your exe. Use the static C-Runtime option, so that the C-Runtime will be used as static lib, its useful if you don't have a lot of dll/exe.
950,334
950,386
What is the good cross platform C++ IDE?
It needs to have good code completion support, debugger, and a nice way to browse code (click to go to documentation). Since I got spoiled by Java IDEs (Eclipse), it would be cool if it supported refactoring, reference search and some form of on the fly compilation, but maybe I'm asking too much. So far I tried Eclipse C++ plugin, Qt Creator and Code Blocks. Eclipse plugin feels sluggish, Code Blocks has much worse completion then Qt Creator and Qt Creator is great for Qt stuff, but kinda hard to use for free form projects. What are other options and first hand experience with them, since trying something for few hours and using something on a daily basis are two different things?
I have been using Code Lite for some time now. It provides support for auto completion. It has a code explorer and outline, though I find myself using "find resource" to open files. It has a plugin for UnitTest++ and some primitive refactoring capabilities. link text
950,936
950,948
C++ math functions problem (under Linux)
I'm having problem regarding max and sqrt If I include math.h it coudn't find sqrt. So I view the cmath header file and inside it includes math.h, but when I try to open math.h it says that file is not found. SO ithink my math.h is missing in Linux.
Sorry I found the answer. I just need to write it this way: std::max std::sqrt But Why does it work without "std::" under Windows OS?
951,119
952,644
strcpy... want to replace with strcpy_mine which will strncpy and null terminate
The clue is in the title but basically I've inherited some code which has 800+ instances of strcpy. I want to write a new function and then to replace strcpy with strcpy_mine. So I'm trying to work out what parameter list strcpy_mine will have. I tried: void strcpy_mine( char* pTarget, const char* const pCopyMe ) { const unsigned int lenAlwaysFour = sizeof(pCopyMe ); //:( strncpy( pTarget, pCopyMe, lenAlwaysFour ); //add extra terminator in case of overrun pTarget[lenAlwaysFour] = 0; } but the sizeof is always 4 pCopyMe is a pointer what I don't want to do is replace strcpy (buf, pCopyMe); with strncpy (buf, pCopyMe, sizeof(pCopyMe)); buf[sizeof(pCopyMe)] = 0; Any ideas? (strcpy_l isn't available)
Depending on how the call-sites look like, often majority of cases can be handled by a simple template: #include <string.h> template <int bufferSize> void strcpy_mine( char (&pTarget)[bufferSize], const char* const pCopyMe ) { strncpy( pTarget, pCopyMe, bufferSize-1 ); //add extra terminator in case of overrun pTarget[bufferSize-1] = 0; } int main() { char buf[128]; strcpy_mine(buf,"Testing"); return 0; } If you are using Microsoft Visual Studio 2005 or newer, see Secure Template Overloads for a Microsoft implementation.
951,234
951,245
Forward declaration of nested types/classes in C++
I recently got stuck in a situation like this: class A { public: typedef struct/class {…} B; … C::D *someField; } class C { public: typedef struct/class {…} D; … A::B *someField; } Usually you can declare a class name: class A; But you can't forward declare a nested type, the following causes compilation error. class C::D; Any ideas?
You can't do it, it's a hole in the C++ language. You'll have to un-nest at least one of the nested classes.
951,513
952,350
Where can I find API documentation for Windows Mobile phone application skin?
I have to customize the look of Windows Mobile (5/6) dialer application. From bits and pieces of information and the actual custom skin implementations in the wild I know that it is actually possible to change a great deal. I am looking for ways to change the look and feel of the following screens: Actual dialer (buttons, number display, etc.) Incoming call notification Outgoing call screen In-call screen At least in the HTC Fuze device there is a custom skin that can be enabled or disabled, and it is actually a dll. Can anyone point me to a section in MSDN, any kind of sample code, or at least mention the keyword I should be looking for? Edit: There seem to be a number of "skins" for download. How do they do it?
There is currently no API for the default phone dailer and you can't replace it. The only people that can are the OEM's that make the devices. I beleave you can add a context menu extender but I can't find the sample but that's about it. As the other post article link goes into, there are enough API's in WM that you can write your own dailer and kind of replace it in most cases. Altho you can detect incomming calls you may be out of luck displaying a GUI in all situations (e.g. when the phone is locked).
952,789
953,494
Using Visual Studio 6 C++ compiler from within Emacs
I'm just getting started with c++ development and I would like to use emacs to write the code and then compile and run it from within emacs using the visual studio 6 compiler. I have already googled around a bit but just can't seem to find an explanation of how this is done. Any pointers? Thanks for your help, joerg
I have done this as a matter of course over the past few years. There are two ways to do this: In the older versions of VS (including VS 6.0), there is a button to export the nmake file for the project. I do this on occasion and then use nmake to compile. I have (setq compile-command "nmake debug ") in my .xemace/init.el for this. You have to add the name of the nmake file, and nmake.exe has to be in your path. (BTW, I modified compilation-error-regexp-alist-alist to help moving through the errors. Let me know if you want this as well.) Newer versions of VS do not have the button to export the nmake file. For these I call devenv.com. In this case I have (setq compile-command "devenv.com /build Debug ") in my .xemacs/init.el. You have to add the name of the .sln file. Although I did not do this with VS 6.0, I believe that it may work as well.
952,888
952,928
map.erase( map.end() )?
Consider: #include <map> int main() { std::map< int, int > m; m[ 0 ] = 0; m[ 1 ] = 1; m.erase( 0 ); // ok m.erase( 2 ); // no-op m.erase( m.find( 2 ) ); // boom! } (OK, so the title talks abouting erasing an end() iterator, but find will return end() for a non-existent key.) Why is erasing a non-existent key OK, yet erasing end() blows up. I couldn't see any explicit mention of this in the standard? I've tried this on VS2005 (throws an exception in debug configuration) and GCC 4.0.1 (100% CPU). Is it implementation dependent? Thanks.
For erase(key), the standard says that all elements with value key are removed. There may of course be no such values. For erase(it) (where it is a std::map::iterator), the standard says that the element pointed to by it is removed - unfortunately, if it is end() it does not point to a valid element and you are off in undefined behaviour land, as you would be if you used end() for any other map operation. See section 23.1.2 for more details.
952,907
952,963
practices on when to implement accessors on private member variables rather than making them public
I know the differences between public member variables and accessors on private member variables, and saw a few posts already on stack overflow about this. My question has more to do with practices though. Other than not breaking class invariants, what would usually be criterias in terms of practicality to make the member variables to be public rather than private with accessors, and vice versa? Thanks in advance for the advices.
Using an accessor will enforce the client to treat the members as functions, not as raw memory. For instance it will not allow taking the address of said member. So even if the member is as POD as a simple int I still use a get-set pair of function for it. This pays of in the long run as refactoring can change the implementation w/o surprises like 'oh wait, I was taking a void* to your member'. Performance wise all compiler will inline this set/get accessors and the assembly will look just as if referencing a public member field. I don't think in the past 5 years I ever wrote a class that exposed its members public.
953,163
953,204
Disable gcc warning for incompatible options
I'm curious if there is an option to disable gcc warnings about a parameter not being valid for the language being compiled. Ex: cc1: warning: command line option "-Wno-deprecated" is valid for C++/Java/ObjC++ but not for C Our build system passes the warnings we have decided on globally across a build. We have both C/C++ code and the warnings get real annoying when trying to find actual warnings. Any suggestions?
It seems to me that if there were such an option, there would have to be a further option to turn off warnings about that option, and so on infinitely. So I suspect there isn't. Having the same options for builds of completely different languages seems a bit odd anyway - I would have different options defined as makefile macros and used appropriately for different targets.
953,166
954,445
What is the purpose of typedefing a class in C++?
I've seen code like the following frequently in some C++ code I'm looking at: typedef class SomeClass SomeClass; I'm stumped as to what this actually achieves. It seems like this wouldn't change anything. What do typedefs like this do? And if this does something useful, is it worth the extra effort?
See this previous answer to a related question. It's a long quote from a Dan Saks article that explains this issue as clearly as anything I've come across: Difference between 'struct' and 'typedef struct' in C++? The technique can prevent actual problems (though admittedly rare problems). It's a cheap bit of insurance - it's zero cost at runtime or in code space (the only cost is the few bytes in the source file), but the protection you get is so small that it's uncommon to see someone use it consistently. I have a 'new class' snippet that includes the typedef, but if I actually code up a class from scratch without using the snippet, I almost never bother (or is it remember?) to add the typedef. So I'd say I disagree with most of the opinions given here - it is worth putting those typedefs in, but not enough that I'd give anyone (including myself) grief about not putting them in. I've been asked for an example of how not having a class name typedef'ed can result in unexpected behavior - here's an example lifted more or less from the Saks article: #include <iostream> #include <string> using namespace std; #if 0 // change to #if 1 to get different behavior // imagine that this is buried in some header // and even worse - it gets added to a header // during maintenance... string foo() { return "function foo... \n"; } #endif class foo { public: operator string() { return "class foo...\n"; } }; int main() { string s = foo(); printf( "%s\n", s.c_str()); return 0; } When the function declaration is made visible, the behavior of the program silently changes because there is no name conflict between the function foo and the class foo. However, if you include a "typedef class foo foo;" you'll get a compile time error instead of a silent difference in behavior.
953,454
953,506
Sending notifications from C++ DLL to .NET application
I'm writing a C++ DLL that needs to notify client applications. In C++ (MFC), I can register a client window handle inside the DLL, then call PostMessage when I need to notify the client about something. What can I do when the client is a C# application?
You can override the WndProc method in the C# window to handle this specific message protected override void WndProc(ref Message m) { if (m.Msg = YOUR_MESSAGE) { // handle the notification } else { base.WndProc(ref m); } }
953,710
953,731
inline function linker error
I am trying to use inline member functions of a particular class. For example the function declaration and implementation without inlining is as such: in the header file: int GetTplLSize(); in the .cpp file: int NeedleUSsim::GetTplLSize() { return sampleDim[1]; } For some reason if I put the "inline" keyword in either one of the implementation and declaration, as well as in both places, I get linker errors as shown: Creating library C:\DOCUME~1\STANLEY\LOCALS~1\TEMP\MEX_HN~1\templib.x and object C:\DOCUME~1\STANLEY\LOCALS~1\TEMP\MEX_HN~1\templib.exp mexfunction.obj : error LNK2019: unresolved external symbol "public: int __thiscall NeedleUSsim::GetTplLSize(void)" (?GetTplLSize@NeedleUSsim@@QAEHXZ) referenced in function _mexFunction mexfunction.mexw32 : fatal error LNK1120: 1 unresolved externals C:\PROGRA~1\MATLAB\R2008B\BIN\MEX.PL: Error: Link of 'mexfunction.mexw32' failed. What needs to be in order to get rid of this error (i.e. what am I doing wrong in terms of making these inline member functions)?
You need to put function definition into the header then. The simplest way to hint the compiler to inline is to include method body in the class declaration like: class NeedleUSsim { // ... int GetTplLSize() const { return sampleDim[1]; } // ... }; or, if you insist on separate declaration and definition: class NeedleUSsim { // ... int GetTplLSize() const; // ... }; inline int NeedleUSsim::GetTplLSize() const { return sampleDim[1]; } The definition has to be visible in each translation unit that uses that method.
954,015
954,045
Using shared C++/STL code with Objective-C++
I have a lot of shared C++ code that I'd like to use in my iPhone app. I added the .cpp and .h files to my Xcode project and used the classes in my Objective-C++ code. The project compiles fine with 0 errors or warnings. However, when I run it in the simulator I get the following error when I attempt to access an STL method in my objective-c code (such as .c_str()): Program received signal: “EXC_BAD_ACCESS”. Unable to disassemble std::string::c_str. Here's an example of the code that causes the error: [name setText:[[NSString alloc] initWithCString:myCPlusPlusObject->cppname.c_str()]]; where name is an NSTextField object and cppname is a std::string member of myCPlusPlusObject. Am I going about this the right way? Is there a better way to use STL-laden C++ classes in Objective-C++? I would like to keep the common C++ files untouched if possible, to avoid having to maintain the code in two places. Thanks in advance!
Make sure the string isn't empty before passing it to the initWithCString function. Also the function you're using has been deprecated, use this one instead.
954,261
954,278
Can one decode real media file to other media formats using any free C++ library?
Please provide some pointers on how to convert real media formats to other popular media formats using some C++ sdk(I guess Helix provides one but don't know how to use it). I am a total newbie in the above area, any help would be highly appreciated.
libavcodec (a library behind ffmpeg and other heavily-used programs) supports some common Real video formats. See this page; the tutorial itself is obsolete, but there are linked updates such as An ffmpeg and SDL Tutorial Helix may be an option, but keep in mind the actual Real Video codecs are only available as binaries, while libavcode is fully open source. Don't expect this to be trivial, whichever library you use.
954,266
954,308
Recommendations for an open-source project to help an experienced developer practice C++
I'm looking for recommendations for open-source projects written in C++ that will help me "get my chops back". A little background: I've been working heavily in Java for the last three years, doing a lot of back-end development and system design, but with a fair amount of work in the presentation layer stuff, too. The last C++ projects I worked on were a Visual C++ 6 project (designed to interact with Visual Basic) for mobile devices and several projects using the GNU toolchain circa gcc versions 2.x to 3.2 I'm looking to get back up to speed on the language and learn some of the popular frameworks, specifically the basics of boost (although boost seems fairly sprawling to me, similar to the kitchen-sink feel of Spring in the java space) and test driven development in C++. What I'm looking for: Specific recommendations for small to mid-size open source projects to poke through and perhaps contribute to as I level my C++ skills back up. The problem domain isn't important, except that I would like to work on something in a new area to broaden my experience. Edit: A few people have commented that it's difficult to provide a recommendation without some indication of the problem domain I'd like to work in. So, I've decided that I'm most interested in graphics applications or games, two areas which I haven't worked in before.
If you like visual stuff, openFrameworks is a C++ Framework for doing Processing-type applications. http://www.openframeworks.cc/ I'm not sure how viable it still is, but it looked pretty cool. It's hard to suggest something like this, you really don't have any itches you want to scratch??
954,321
956,944
Is it possible to share an enum declaration between C# and unmanaged C++?
Is there a way to share an enum definition between native (unmanaged) C++ and (managed) C#? I have the following enum used in completely unmanaged code: enum MyEnum { myVal1, myVal2 }; Our application sometimes uses a managed component. That C# component gets the enum item values as ints via a managed C++ interop dll (from the native dll). (The interop dll only loads if the C# component is needed.) The C# component has duplicated the enum definition: public enum MyEnum { myVal1, myVal2 }; Is there a way to eliminate the duplication without turning the native C++ dll into a managed dll?
You can use a single .cs file and share it between both projects. #include in C++ on a .cs file should be no problem. This would be an example .cs file: #if !__LINE__ namespace MyNamespace { public #endif // shared enum for both C, C++ and C# enum MyEnum { myVal1, myVal2 }; #if !__LINE__ } #endif If you want multiple enums in one file, you can do this (although you have to temporarily define public to be nothing for C / C++): #if __LINE__ #define public #else namespace MyNamespace { #endif public enum MyEnum { MyEnumValue1, MyEnumValue2 }; public enum MyEnum2 { MyEnum2Value1, MyEnum2Value2 }; public enum MyEnum3 { MyEnum3Value1, MyEnum3Value2 }; #if __LINE__ #undef public #else } #endif
954,548
954,565
How to pass a function pointer that points to constructor?
I'm working on implementing a reflection mechanism in C++. All objects within my code are a subclass of Object(my own generic type) that contain a static member datum of type Class. class Class{ public: Class(const std::string &n, Object *(*c)()); protected: std::string name; // Name for subclass Object *(*create)(); // Pointer to creation function for subclass }; For any subclass of Object with a static Class member datum, I want to be able to initialize 'create' with a pointer to the constructor of that subclass.
You cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors - "12.1-12 Constructors - "The address of a constructor shall not be taken.") Your best bet is to have a factory function/method that creates the Object and pass the address of the factory: class Object; class Class{ public: Class(const std::string &n, Object *(*c)()) : name(n), create(c) {}; protected: std::string name; // Name for subclass Object *(*create)(); // Pointer to creation function for subclass }; class Object {}; Object* ObjectFactory() { return new Object; } int main(int argc, char**argv) { Class foo( "myFoo", ObjectFactory); return 0; }
954,653
954,672
I want to learn COM. How should I proceed?
I am a fresh graduate with a bachelor in Computer Science. As most school today, they are no longer teaching students C or advance C++ (only an Introductory course in C++... With lessons up to Pointers). The standard programming language prescribed in the curriculum is C# (.NET stack). Just recently, I got hired as a junior software developer. 95% of our codebase is in C++ and our products are using COM/DCOM. The other 5% is in .NET. My current responsibility is to maintain a project written in .NET (ASP.NET) and I am not required to study C++ and other technology YET. But I want to learn COM as soon as possible so I can help out on other projects. So I am seeking the advice of this community on how I can go about learning COM. My current questions are the following: Any required reading? (Pre-requisite topics) A Good Site in Learning the basics of COM? A type of Simple Program to really appreciate the "purpose" of COM (A chat program perhaps?) Thanks! :) PS: Should I mark this as a community wiki?
The book of Don Box about COM is the definitive reference. Amazon link. Beware is a tough read, but it covers everything in deep. And remember, as Don said... COM IS LOVE. I do not believe you can find a lot of web site, COM was a up to date technology a lot of time ago, but if you can forgot about it trust me... it's better!
954,731
954,778
Can smart pointers selectively hide or re-direct function calls to the objects they are wrapping?
I'm working on a project where certain objects are referenced counted -- it's a very similar setup to COM. Anyway, our project does have smart pointers that alleviate the need to explicitly call Add() and Release() for these objects. The problem is that sometimes, developers are still calling Release() with the smart pointer. What I'm looking for is a way to have calling Release() from the smart pointer create a compile-time or run-time error. Compile-time doesn't seem possible to me. I thought I had a run-time solution (see code below), but it doesn't quite compile either. Apparently, implicit conversion isn't allowed after using operator->(). Anyway, can anyone think of a way to accomplish what I'm trying to accomplish? Many thanks for your help! Kevin #include <iostream> #include <cassert> using namespace std; class A { public: void Add() { cout << "A::Add" << endl; } void Release() { cout << "A::Release" << endl; } void Foo() { cout << "A::Foo" << endl; } }; template <class T> class MySmartPtrHelper { T* m_t; public: MySmartPtrHelper(T* _t) : m_t(_t) { m_t->Add(); } ~MySmartPtrHelper() { m_t->Release(); } operator T&() { return *m_t; } void Add() { cout << "MySmartPtrHelper::Add()" << endl; assert(false); } void Release() { cout << "MySmartPtrHelper::Release()" << endl; assert(false); } }; template <class T> class MySmartPtr { MySmartPtrHelper<T> m_helper; public: MySmartPtr(T* _pT) : m_helper(_pT) { } MySmartPtrHelper<T>* operator->() { return &m_helper; } }; int main() { A a; MySmartPtr<A> pA(&a); pA->Foo(); // this currently fails to compile. The compiler // complains that MySmartPtrHelper::Foo() doesn't exist. //pA->Release(); // this will correctly assert if uncommented. return 0; }
You can't do it - once you've overloaded the operator -> you're stuck - the overloaded operator will behave the same way reardless of what is rightwards of it. You could declare the Add() and Release() methods private and make the smart pointer a friend of the reference-counting class.
954,945
3,067,953
Large number of simulteneous connections in thrift
I'm trying to write a simple server with Thrift. At the beginning it looked promising, but I've stumbled into a problem with a number of clients connected at the same time. I'm using TThreadPoolServer, which allows 4 client to connect and then blocks other clients until I kill one from the connected. What can I do to allow more (possibly several hundreds) clients to be connected at the same time, without increasing the number of threads. I assumed that the worker threads allow to perform one client request at a time, but it looks like one thread handles one connection until it is closed. I'd like to avoid a situation when my clients has to reopen a socket to perform an action.
Taking another approach, if you are using C++ to build your server, you can use TNonblockingServer instead of TThreadPoolServer, which will allow you to accept many connections at once, regardless of how many threads are active, etc... That being said, you won't necessarily be able to actually do work faster (handlers still execute in a thread pool), but more clients will be able to connect to you at once. Here's what the code looks like for the NB server: shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); shared_ptr<MyHandler> handler(new MyHandler()); shared_ptr<TProcessor> processor(new MyProcessor(handler)); TNonblockingServer server(processor, protocolFactory, port);
955,129
955,204
Cant focus WxWidgets frame in Mac OSX compiled with SCons
I have this WxWidgets test source code that compiles, and when run, it shows a simple frame: /* * hworld.cpp * Hello world sample by Robert Roebling */ #include "wx-2.8/wx/wx.h" class MyApp: public wxApp { virtual bool OnInit(); }; class MyFrame: public wxFrame { public: MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size); void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); DECLARE_EVENT_TABLE() }; enum { ID_Quit = 1, ID_About, }; BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(ID_Quit, MyFrame::OnQuit) EVT_MENU(ID_About, MyFrame::OnAbout) END_EVENT_TABLE() IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { MyFrame *frame = new MyFrame( _T("Hello World"), wxPoint(50,50), wxSize(450,340) ); frame->Show(TRUE); SetTopWindow(frame); return TRUE; } MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame((wxFrame *)NULL, -1, title, pos, size) { wxMenu *menuFile = new wxMenu; menuFile->Append( ID_About, _T("&About...") ); menuFile->AppendSeparator(); menuFile->Append( ID_Quit, _T("E&xit") ); wxMenuBar *menuBar = new wxMenuBar; menuBar->Append( menuFile, _T("&File") ); SetMenuBar( menuBar ); CreateStatusBar(); SetStatusText( _T("Welcome to wxWindows!") ); } void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { Close(TRUE); } void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxMessageBox(_T("This is a wxWindows Hello world sample"), _T("About Hello World"), wxOK | wxICON_INFORMATION, this); } Created with this simple SCons script: env = Environment() env.ParseConfig('wx-config --cxxflags --libs') env.Program(target='wxTest/wxTest.exe',source=['src/Wxwidgets.cpp']) The problem: it wont focus when I run it. The only thing I can focus is the red, yellow and green buttons in the upper left corner. I use Eclipse as my IDE and run scons as an external tool when I build it. Is there someone out there that know what Im doing wrong? How can I get the frame to focus? Hope there is someone out the who can help me.
I assume you start the raw executable that is created? This does not work on Mac OS X, see My app can't be brought to the front! You will have to create an application bundle for your app to work properly on Mac OS X. I don't know anything about SCons, but maybe the wiki does help?
955,162
955,179
missing ; before identifier while compiling VC6 code in VC9
The following code compiles fine in VC6 but when I compile the same project in VS2008 it gives the following error error C2146: syntax error : missing ';' before identifier 'm_pItr' template <class pKey, class Data, class pCompare, class hKey = int, class hCompare = less<hKey>, class sKey = int, class sCompare = less<sKey>, class tKey = int, class tCompare = less<tKey>, class cKey = int, class cCompare = less<cKey>> class GCache { private: typedef map<pKey, Data, pCompare> PRIMARY_MAP; PRIMARY_MAP pMap; PRIMARY_MAP::iterator m_pItr; //error here //Code truncated } Any ideas of what is wrong here? Someone with experience in migrating C++ code from VC6 to VC2005/2008 might be able to help.
You may need to insert 'typename', to tell the compiler PRIMARY_MAP::iterator is, in all cases, a type. e.g. class GCache { private: typedef map<pKey, Data, pCompare> PRIMARY_MAP; PRIMARY_MAP pMap; typename PRIMARY_MAP::iterator m_pItr; //Code truncated }
955,568
955,572
Interfacing MFC and Command Line
I'd like to add a command line interface to my MFC application so that I could provide command line parameters. These parameters would configure how the application started. However, I can't figure out how to interface these two. How could I go about doing this, if it's even possible?
MFC has a CCommandLineInfo class for doing just that - see the CCommandLineInfo documentation.
955,862
955,889
specialised hash table c++
I need to count a lot of different items. I'm processing a list of pairs such as: A34223,34 B23423,-23 23423212,16 What I was planning to do was hash the first value (the key) into a 32bit integer which will then be a key to a sparse structure where the 'value' will be added (all start at zero) number and be negative. Given that they keys are short and alphanumeric, is there an way to generate a hash algorithm that is fast on 32bit x86 architectures? Or is there an existing suitable hash? I don't know anything about the design of hashes, but was hoping that due to the simple input, there would be a way of generating a high performance hash that guarantees no collision for a given key length of "X" and has high dispersion so minimizes collisions when length exceeds "X".
As you are using C++, the first thing you should do is to create a trivial implimentation using std::map. Is it fast enough (it probably will be)? If so, stick with it, otherwise investigate if your C++ implementation provides a hash table. If it does, use it to create a trivial implementation, test, time it. Is it fast enough (almost certainly yes)? Only after you hav eexhausted these options should you think of implementing your own hash table and hashing function.
956,284
956,318
Using C++ Library in Linux (eclipse)
I wrote a library and want to test it. I wrote the following program, but I get an error message from eclipse. #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*desk)(char*); char *error; handle = dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY); if (!handle) { fputs (dlerror(), stderr); exit(1); } desk= dlsym(handle, "Apply"); // ERROR: cannot convert from 'void *' to 'double*(*)(char*)' for argument 1 if ((error = dlerror()) != NULL) { fputs(error, stderr); exit(1); } dlclose(handle); } What is wrong? Regards.
In C++ you need the following: typedef double (*func)(char*); func desk = reinterpret_cast<func>( dlsym(handle, "Apply"));
956,310
956,647
eliminating the inter-compiler incompatibility issue with C++ dynamic libraries
..., a follow up to this. From the answers I've been given to my referenced question I've learned that: different compilers use different name decoration, which makes it impossible to use a C++ dynamic library built with compiler A in a project built with compiler B, the library can be built as static saving me including n header and source files in the project or exporting symbols. (It still won't save rebuilding the library for use with a different compiler.) Having a closer look at SDL in the light of what's been said, I've realized, that its linking has two layers: in my SDL project, I link statically against libSDL.a, which will, in turn, link dynamically against SDL.dll, thereby elminating the need for different .dll versions for different compilers. The question is whether this is really the case and a viable solution to the problem, or am I missing something (and what)?
I think your approach is right. I'd put it this way: For a dll to be usable by different compilers, it must contain only C functions (they can be compiled using a C++ compiler using extern C) As usual with dlls, a static import library can be used so that functions in the dll can be called directly, rather than needing to be loaded by name Instead of a regular import library, you could have a wrapper library that wraps the dll's C functions in C++ classes and functions
956,504
956,548
Would std::basic_string<TCHAR> be preferable to std::wstring on Windows?
As I understand it, Windows #defines TCHAR as the correct character type for your application based on the build - so it is wchar_t in UNICODE builds and char otherwise. Because of this I wondered if std::basic_string<TCHAR> would be preferable to std::wstring, since the first would theoretically match the character type of the application, whereas the second would always be wide. So my question is essentially: Would std::basic_string<TCHAR> be preferable to std::wstring on Windows? And, would there be any caveats (i.e. unexpected behavior or side effects) to using std::basic_string<TCHAR>? Or, should I just use std::wstring on Windows and forget about it?
I believe the time when it was advisable to release non-unicode versions of your application (to support Win95, or to save a KB or two) is long past: nowadays the underlying Windows system you'll support are going to be unicode-based (so using char-based system interfaces will actually complicate the code by interposing a shim layer from the library) and it's doubtful whether you'd save any space at all. Go std::wstring, young man!-)
956,546
956,566
CreateFile Win32 API Call with OPEN_ALWAYS failed in an Odd Way
We had a line of code if( !CreateFile( m_hFile, szFile, GENERIC_READ|GENERIC_WRITE, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL ) ) { DWORD dwErr = GetLastError(); CString czInfo; czInfo.Format ("CMemoryMapFile::OpenAppend SetFilePointer call failed - GetLastError returned %d", dwErr); LOG(czInfo); return false; } This code worked great for many years. A few weeks ago, we had a customer with a problem. Turns out, the problem could be traced to this line of code, where the function would return a INVALID_HANDLE_VALUE handle and GetLastError() returned ERROR_FILE_NOT_FOUND(2). Now, this is very confusing to us. OPEN_ALWAYS should direct the file to be created if it does not exist. So, why are we getting a ERROR_FILE_NOT_FOUND? More confusion: For this customer, this only happened on one network share point (we were using a UNC path). Other UNC paths to other machines for this customer worked. Local paths worked. All our other customers (10000+ installs) have no problem at all. The customer was using XP as the client OS, and the servers were running what appeared to be standard Windows Server 2003 (I think the Small Business Server version). We could not replicate their errors in our test lab using the same OS's. They could repeat the problem with several XP clients, but the problem was only on one server (other Server 2003 servers did not exhibit the problem). We fixed the problem by nesting two CreateFile calls, the first with OPEN_EXISTING, and the second with CREATE_ALWAYS if OPEN_EXISTING failed. So, we have no immediate need for a fix. My question: Does anyone have any idea why this API call would fail in this particular way? We are puzzled. Addendum: The CreateFile function above is a wrapper on the Windows API function. Here's the code: bool CMemoryMapFile::CreateFile( HANDLE & hFile, LPCSTR szFile, DWORD dwDesiredAccess, DWORD dwShareMode, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes ) { hFile = ::CreateFile (szFile, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); return (hFile != INVALID_HANDLE_VALUE) }
Maybe the directory you wanted to create the file in did not exist? Are you sure you fixed it by using 2 CreateFile calls? Or did you just not reproduce it?
956,611
956,864
unique_ptr - major improvement?
In the actual C++ standard, creating collections satisfying following rules is hard if not impossible: exception safety, cheap internal operations (in actual STL containers: the operations are copies), automatic memory management. To satisfy (1), a collection can't store raw pointers. To satisfy (2), a collection must store raw pointers. To satisfy (3), a collection must store objects by value. Conclusion: the three items conflict with each other. Item (2) will not be satisfied when shared_ptrs are used because when a collection will need to move an element, it will need to make two calls: to a constructor and to a destructor. No massive, memcpy()-like copy/move operations are possible. Am I correct that the described problem will be solved by unique_ptr and std::move()? Collections utilizing the tools will be able to satisfy all 3 conditions: When a collection will be deleted as a side effect of an exception, it will call unique_ptr's destructors. No memory leak. unique_ptr does not need any extra space for reference counter; therefore its body should be exact the same size, as wrapped pointer, I am not sure, but it looks like this allows to move groups of unique_ptrs by using memmove() like operations (?), even if it's not possible, the std::move() operator will allow to move each unique_ptr object without making the constructor/destructor pair calls. unique_ptr will have exclusive ownership of given memory. No accidental memory leaks will be possible. Is this true? What are other advantages of using unique_ptr?
I agree entirely. There's at last a natural way of handling heap allocated objects. In answer to: I am not sure, but it looks like this allows to move groups of unique_ptrs by using memmove() like operations, there was a proposal to allow this, but it hasn't made it into the C++11 Standard.
956,640
956,698
Linux c++ error: undefined reference to 'dlopen'
I work in Linux with C++ (Eclipse), and want to use a library. Eclipse shows me an error: undefined reference to 'dlopen' Do you know a solution? Here is my code: #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*desk)(char*); char *error; handle = dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY); if (!handle) { fputs (dlerror(), stderr); exit(1); } desk= dlsym(handle, "Apply"); if ((error = dlerror()) != NULL) { fputs(error, stderr); exit(1); } dlclose(handle); }
You have to link against libdl, add -ldl to your linker options
956,658
956,695
Can you use C++ templates to specify a collection type and the specialization of that type?
Example, I want to specialize a class to have a member variable that is an stl container, say a vector or a list, so I need something like: template <class CollectionType, class ItemType> class Test { public: CollectionType<ItemType> m_collection; }; So I can do: Test t = Test<vector, int>(); t.m_collection<vector<int>> = vector<int>(); But this generates test.cpp:12: error: `CollectionType' is not a template
Why not do it like this? template <class CollectionType> class Test { public: CollectionType m_collection; }; Test t = Test<vector<int> >(); t.m_collection = vector<int>(); If you need the itemtype you can use CollectionType::value_type. EDIT: in response to your question about creating a member function returning the value_type, you do it like this: typename CollectionType::value_type foo(); You add the typename because CollectionType has not been bound to an actual type yet. So there isn't a value_type it could look up.
956,764
956,791
Collection specialized for shared_ptr
Does there exist a collection, that is aware of shared_ptr internals, and avoids regular copying of stored shared_ptr elements in favor of just copying their internal weak pointer? This implicitly means, that no constructor/destructor calls will be done and that there will be no manipulation of shared_ptrs' reference counters.
that is aware of shared_ptr internals, That should answer your question right there. To be aware of the internals, such a collection would almost certainly have to be part of boost's smart pointer libraries. Unfortunately, there is no such thing. This is indeed a downside to smart pointers. I would recommend using data structures that limit the number of copies done internally. Vector's reallocations will be painful. Perhaps a deque, which has a chunked based allocation, would be useful. Keep in mind too that vector implementations tend to get new memory in exponentially increasing chunks. So they don't reallocate, say, every 10 elements. Instead you might start out with 128 elements, then the vector reserves itself 256, then moves up to 512, 1024, etc. Each time doubling what is needed. Short of this there's boost's ptr_vector or preallocating your data structures with enough space to prevent internal copying.
956,779
956,800
C++ iterator problems
I have the following member data vector<State<T>*> activeChildren; I want to clean-up these pointers in my destructor StateContainer<T>::~StateContainer() { vector<State<T>*>::iterator it = activeChildren.begin(); while(it!=activeChildren.end()) { State<T>* ptr = *it; it = activeChildren.erase(it); delete ptr; } } I get the following error from g++ 4.3.2 on Ubuntu: ./fsm2/StateContainer.cpp: In destructor ‘virtual ervan::StateContainer<T>::~StateContainer()’: ../fsm2/StateContainer.cpp:24: error: expected `;' before ‘it’ ../fsm2/StateContainer.cpp:25: error: ‘it’ was not declared in this scope Can anyone tell me what I've done wrong? I get this error in two more places where I use iterator loops, but not when I use for_each(...)
Looks like typename time again - I think you need: typename vector<State<T>*>::iterator it = ... A heuristic for g++ users - when you see this message in template code: expected `;' before ‘it’ it is a pretty good bet that the thing in front of the 'it' is not being seen by the compiler as a type and so needs a 'typename' added.
956,811
1,061,375
VS2008 C++ app fails to start in Debug mode: This application has failed to start because MSVCR90.dll was not found
I've got a minimal app I just created, using VS 2008 SP1 on Vista x64. Its a Console app, created with the wizard, no MFC or anything, I'm building it in 64bit. When I run the debug exe, on my development box, by pressing F5 in Visual Studio 2008, I get this error: TestApp.exe - Unable To Locate Component This application has failed to start because MSVCR90.dll was not found. Re-installing the application may fix this problem. OK I don't get this error when I run the release exe, it works as expected. This problem started when I added some include dependencies on iostream and fstream and started calling some winsock API calls. Any suggestions? UPDATE: I copied msvcr90.dll (not msvcrd90.dll) into the correct folder, and now I get a different error: Microsoft Visual C++ Runtime Library Runtime Error! Program: [snip]... R6034 An application has made an attempt to load the C runtime library incorrectly. Please contact the application's support team for more information. OK Alex
Thanks again for all the help with this. It turns out I'd just made a mistake and not noticed that a library I was using was statically linked against a different version of the MSVC runtime. That was causing on end of problems.
957,057
957,132
What is the MZ signature in a PE file for?
I'm working on a program that will parse a PE object for various pieces of information. Reading the specifications though, I cannot find out why the MZ bytes are there, as I cannot find this on the list of machine types that these 2 bytes are supposed to represent. Can anyone clarify?
The MZ signature is a signature used by the MS-DOS relocatable 16-bit EXE format. The reason a PE binary contains an MZ header is for backwards compatibility. If the executable is run on a DOS-based system it will run the MZ version (which is nearly always just stub that says you need to run the program on a Win32 system). Of course this is not as useful nowadays as it was back when the world was transitioning from DOS to whatever would come after it. Back then there were a few programs that would actually bind together a DOS version and a Win32 version in a single binary. And as with most things dealing with Windows history, Raymond Chen has some interesting articles about this subject: Why does a corrupted binary sometimes result in "Program too big to fit in memory"? What's the difference between the COM and EXE extensions?
957,087
957,111
When is it preferable to store data members as references instead of pointers?
Let's say I have an object Employee_Storage that contains a database connection data member. Should this data member be stored as a pointer or as a reference? If I store it as a reference, I don't have to do any NULL checking. (Just how important is NULL checking anyway?) If I store it as a pointer, it's easier to setup Employee_Storage (or MockEmployee_Storage) for the purposes of testing. Generally, I've been in the habit of always storing my data members as references. However, this makes my mock objects difficult to set up, because instead of being able to pass in NULLs (presumably inside a default constructor) I now must pass in true/mock objects. Is there a good rule of thumb to follow, specifically with an eye towards testability?
It's only preferable to store references as data members if they're being assigned at construction, and there is truly no reason to ever change them. Since references cannot be reassigned, they are very limited. In general, I typically store as pointers (or some form of templated smart pointer). This is much more flexible - both for testing (as you mentioned) but also just in terms of normal usage.
957,310
958,208
suggestions on a project in C++ / distributed systems / networks
I'd like to work on a 2-3 month long project (full time) that involves coding in C++ and is related to networks (protocol stacks). I was considering writing my own network stack but that doesn't seem as interesting. It would be great to find an idea to implement a tcp/ip-like stack for distributed system/GPUs that is better as far as network performance goes. I have been googling this for 3 hours but haven't come across anything that seems worth spending 2 months on. Open source projects like netperf seem beyond my scope. I'd really like a relatively small stand alone project that I can work on, at my own pace. The intent of this project is to utilize my free time on a project (that I might later release under open source license) and gain expertise and hands-on experience in C++, networks, parallel programming, GPU, distributed systems etc. I seem to have hit a roadblock while finding ideas (or perhaps I am not too clear on what I exactly what to do). So any suggestions would be really appreciated. Thanks!
If you are specifically interested in doing network programming with an emphasis on distribution and GPU/graphics stuff, you may want to check out the open source (GPL) CIGI project (sourceforge project site: CIGI is an open simulation protocol for communication between a host device and IG (image generator). The Common Image Generator Interface (CIGI) is an interface designed to promote a standard way for a host device to communicate with an image generator (IG) in the simulation industry. CIGI is a fairly active project on sourceforge, initiated and backed by BOEING, and is multi-platform software: The goal of the Common Image Generator Interface (CIGI) SG is to evaluate industry and government interest in developing a standard image generator interface. Typically, today's Image Generator (IG) vendors have their own closed, proprietary run-time interfaces. At I/ITSEC'02, Boeing proposed their Open Source Common Image Generator Interface (CIGI) as a run-time interface that could be adopted by the simulation community. Boeing indicated that they would like to see a standards organization adopt CIGI and develop it into a robust and broadly accepted simulation industry image generator run-time interface standard. The SG is discussing this proposal, evaluating alternatives, and generating recommendations and a proposed action plan. Here's some wireshark-based info on CIGI
957,838
957,947
Enforce static method overloading in child class in C++
I have something like this: class Base { public: static int Lolz() { return 0; } }; class Child : public Base { public: int nothing; }; template <typename T> int Produce() { return T::Lolz(); } and Produce<Base>(); Produce<Child>(); both return 0, which is of course correct, but unwanted. Is there anyway to enforce the explicit declaration of the Lolz() method in the second class, or maybe throwing an compile-time error when using Produce<Child>()? Or is it bad OO design and I should do something completely different? EDIT: What I am basically trying to do, is to make something like this work: Manager manager; manager.RegisterProducer(&Woot::Produce, "Woot"); manager.RegisterProducer(&Goop::Produce, "Goop"); Object obj = manager.Produce("Woot"); or, more generally, an external abstract factory that doesn't know the types of objects it is producing, so that new types can be added without writing more code.
There are two ways to avoid it. Actually, it depends on what you want to say. (1) Making Produce() as an interface of Base class. template <typename T> int Produce() { return T::Lolz(); } class Base { friend int Produce<Base>(); protected: static int Lolz() { return 0; } }; class Child : public Base { public: int nothing; }; int main(void) { Produce<Base>(); // Ok. Produce<Child>(); // error :'Base::Lolz' : cannot access protected member declared in class 'Base' } (2) Using template specialization. template <typename T> int Produce() { return T::Lolz(); } class Base { public: static int Lolz() { return 0; } }; class Child : public Base { public: int nothing; }; template<> int Produce<Child>() { throw std::bad_exception("oops!"); return 0; } int main(void) { Produce<Base>(); // Ok. Produce<Child>(); // it will throw an exception! }
958,003
958,092
How to manage special cases and heuristics
I often have code based on a specific well defined algorithm. This gets well commented and seems proper. For most data sets, the algorithm works great. But then the edge cases, the special cases, the heuristics get added to solve particular problems with particular sets of data. As number of special cases grow, the comments get more and more hazy. I fear going back and looking at this code in a year or so and trying to remember why each particular special case or heuristic was added. I sometimes wish there was a way to embed or link graphics in the source code, so I could say effectively, "in the graph of this data set, this particular feature here was causing the routine to trigger incorrectly, so that's why this piece of code was added". What are some best-practices to handle situations like this? Special cases seem to be always required to handle these unusual/edge cases. How can they be managed to keep the code relatively readable and understandable? Consider an example dealing with feature recognition from photos (not exactly what I'm working on, but the analogy seems apt). When I find a particular picture for which the general algorithm fails and a special case is needed, I record as best I can that information in a comment, (or as someone suggested below, a descriptive function name). But what is often missing is a permanent link to the particular data file that exhibits the behavior in question. While my comment should describe the issue, and would probably say "see file foo.jp for an example of this behavior", this file is never in the source tree, and can easily get lost. In cases like this, do people add data files to the source tree for reference?
If you have a knowledge base or a wiki for the project, you could add the graph in it, linking to it in the method as per Matthew's Fowler quote and also in the source control commit message for the edge case change. //See description at KB#2312 private object SolveXAndYEdgeCase(object param) { //modify param to solve for edge case return param; } Commit Message: Solution for X and Y edge case, see description at KB#2312 It is more work, but a way to document cases more thoroughly than mere test cases or comments could. Even though one might argue that test cases should be documentation enough, you might not want store the whole failing data set in it, for instance. Remember, vague problems lead to vague solutions.
958,374
958,501
Correct formatting of numbers with errors (C++)
I have three sets of numbers, a measurement (which is in the range 0-1 inclusive) two errors (positive and negative. These numbers should be displayed consistently to the number of significant figures, rounded up, which corresponds to the first non-zero entry in either of the number. This requirement is skipped on the measurement if it is one (i.e. only the figures in the errors need be considered). For example: 0.95637 (+0.00123, -0.02935) --> 0.96 +0.00 -0.03 1.00000 (+0.0, -0.0979) --> 1.0 +0.0 -0.1 (note had to truncate due to -ve error rounding up at first significant digit) Now, getting at the first non-zero digit is easy by taking log10(num), but I'm having an idiotic moment trying to get stripping and rounding working in a clean fashion. All data types are doubles, and language of choice is C++. All and any ideas welcome!
My C++ is rusty, but wouldn't the following do it: std::string FormatNum(double measurement, double poserror, double negerror) { int precision = 1; // Precision to use if all numbers are zero if (poserror > 0) precision = ceil(-1 * log10(poserror)); if (negerror < 0) precision = min(precision, ceil(-1 * log10(abs(negerror)))); // If you meant the first non-zero in any of the 3 numbers, uncomment this: //if( measurement < 1 ) // precision = min(precision, ceil(-1 * log10(measurement))); stringstream ss; ss.setf(ios::fixed, ios::floatfield); ss.precision( precision ); ss << measurement << " +" << poserror << " " << negerror ; return ss.str(); }
958,456
958,633
C/C++ Reflection and JNI - A method for invoking native code which hasn't been written yet
I am implementing a piece of Java software that will hopefully allow for C libraries as plugins. In order to call these future functions, I need to somehow create a native function in Java from which I can call the code that doesn't exist yet. The method signature will be static but the method and class names may change. Is there a way to check the loaded libraries or available functions? The way I hope it would work would be as follows: In my Java class I would have a function; public static native void thirdParty(String class, String method, int[] data, int[] params); Which would call a function in my C library; JNIEXPORT void JNICALL Java_com_ex_app_Native_thirdParty(JNIEnv *, jclass, jstring, jstring, jintArray, jintArray); From which I could take the class and method name and call them if they exist and throw an exception if they don't. I guess what I'm looking for is some kind of Java style reflection but in C or failing that C++. How can I achieve this?
The standard way (or common since there is no real standard) Is to create a DLL (shared lib). That DLL has a "C" function with a a fixed name that returns a pointer to a factory object. You can then use the factory to build objects. Example: DLL-> Wdigets1.dll C function -> extern "C" Fac& getWidgetFactory(); DLL-> BoilerWidget.dll C function -> extern "C" Fac& getWidgetFactory(); DLL-> RoundWidget.dll C function -> extern "C" Fac& getWidgetFactory(); Thus whatever dll you load all you need to do is get a pointer to the function getWidgetFactory() and now you can use the factory to build the appropriate widgets. The reason behind this: The libraries that allow you to load libraries dynamically also allow you to find methods/function by name. But the name you need to use is the full name. In "C" this is well defined. In "C++" this is the mangeled name and varies across compilers/platforms etc. So portable code can only find "C" names.
958,464
958,519
Are there any tools for parsing a Visual c++ generated resource script?
Are there any tools for parsing a Visual c++ generated resource script? Is this resource script's format documented any where? I am looking for something in MFC or .net that could parse some data out of the files for reporting.
I do not know of any tools for parsing this, but the format is described in detail at this site. The resource script files are an ASCII text format, so it should be fairly easy to parse out the information you need.
958,625
958,651
In C++, when can two variables of the same name be visible in the same scope?
This code illustrates something that I think should be treated as bad practice, and elicit warnings from a compiler about redefining or masking a variable: #include <iostream> int *a; int* f() { int *a = new int; return a; } int main() { std::cout << a << std::endl << f() << std::endl; return 0; } Its output (compiled with g++): 0 0x602010 I've looked at a couple references (Stroustrup and The Complete C++ Reference) and can't find anything about when and why this is allowed. I know that it's not within a single local scope, though. When and why is this allowed? Is there a good use for this construct? How can I get g++ to warn me about it? Do other compilers squawk about it?
It's allowed so that you can safely ignore global identifier overriding. Essentially, you only have to be concerned with global names you actually use. Suppose, in your example, f() had been defined first. Then some other developer added the global declaration. By adding a name, f() which used to work, still works. If overriding was an error, then the function would suddenly stop working, even though it doesn't do anything at all with the newly added global variable.
958,695
958,699
C++ Compiler for Windows without IDE?
I'm looking for just a compiler for C++ (such as g++) for Windows, that I could run in my cmd. I'm using notepad++ as my text editor and I want to set up a macro in there that can compile my programs for me. I do not wish to install Cygwin though. Any suggestions?
MinGW. It's GCC/G++ for Windows. It's much lighter than Cygwin. The main difference from Cygwin GCC is that it doesn't try to emulate UNIX APIs, you have to use the Windows APIs (and of course the standard C/C++ libraries). It also doesn't provide a shell and utilities like Cygwin, just the compiler. There is also a related system called MSYS, which provides a shell, etc. like Cygwin, but this is not required. MinGW itself will run in CMD (but I highly suggest using something better like Bash, for your own sanity).
958,865
958,871
Simple Question: Passing object with state, C++
I'm not an C++ expert and still do not have a great intuitive grasp of how things works. I think this is a simple question. I am having trouble passing objects with state to other objects. I'd prefer to avoid passing pointers or references, since once the initialized objects are setup, I call them millions of times in a tight loop. I think I'm dong something like a Command pattern. Here's the core of the problem. My header code is something like: class ObjectWithState { public: ObjectWithState(int state) { // This constructor creates the problem! state_ = state; // everyting works with no constructor. } private: int state_; }; class TakesObject { public: TakesObject(ObjectWithState obj) { obj_ = obj; } private: ObjectWithState obj_; }; My main() functions looks like: int main () { ObjectWithState some_object(1); TakesObject takes_object(some_object); return 0 } I get the following error (g++): test.h: In constructor 'TakesObject::TakesObject(ObjectWithState)': test.h:14: error: no matching function for call to 'ObjectWithState::ObjectWithState()' test.h:5: note: candidates are: ObjectWithState::ObjectWithState(int) test.h:3: note: ObjectWithState::ObjectWithState(const ObjectWithState&) Simple answer? I not sure if this has to do with copy constructors. If so, I'm trying to find a solution that keeps the class definition of ObjectWithState very clean and short. Users of this library will be defining lots of small functions like that which will be used by TakesObject function. Ideally programmers of the ObjectsWithState just need to focus on implementing a simple object. Perhaps I'm going astray...
What you may want to do is use the member initialisation syntax: class TakesObject { public: TakesObject(ObjectWithState obj): obj_(obj) { } private: ObjectWithState obj_; }; In your posted code, the TakesObject constructor will first try to construct a new ObjectWithState with its default constructor, then call the assignment operator to copy the passed-in obj to obj_. The above example constructs the obj_ directly using its copy constructor. You will also need to define a copy constructor for your ObjectWithState class, too: class ObjectWithState { public: ObjectWithState(int state) { state_ = state; } ObjectWithState(const ObjectWithState &rhs) { state_ = rhs.state_; } private: int state_; }; If you omit all constructors from your class declaration, then the compiler supplies a default and a copy constructor for you. If you declare any constructors, then the compiler supplies no default or copy constructor, so you must implement your own.
959,067
959,105
trapping http/https requests in windows
Is it possible to trap http/https requests for filtering in windows?
If you need to sniff the packets, you could use Ethereal or Wireshark Update: Try WinPcap then it gives you a lot of features along with the popular *nix Library libpcap API
959,183
959,214
Appending ints to char* and then clearing
I'm working on a project using an Arduino and as such, I'm reading from a serial port (which sends ints). I need to then write this serial communication to an LCD, which takes a char*. I need to read several characters from the serial port (two integers) into a string. After both have been received, I then need to clear the string to prepare for the next two characters. TLDR: How do I append an int to a char*, and then clear the string after it has two characters?
A char is a single character, whereas a char* can be a pointer to a character or a pointer to the first character in a C string, which is an array of chars terminated by a null character. You can't use a char to represent an integer longer than 1 digit, so I'm going to assume you did in fact mean char*. If you have char buffer[10]; then you can set buffer to a string representing an int n with sprintf sprintf(buffer, "%d", n); And when you're done with it, you can clear the string with sprintf(buffer, ""); Hope that's what you were asking for, and good luck!
959,193
959,201
How to declare factory-like method in base class?
I'm looking for solution of C++ class design problem. What I'm trying to achieve is having static method method in base class, which would return instances of objects of descendant types. The point is, some of them should be singletons. I'm writing it in VCL so there is possibility of using __properties, but I'd prefer pure C++ solutions. class Base { private: static Base *Instance; public: static Base *New(void); virtual bool isSingleton(void) = 0; } Base::Instance = NULL; class First : public Base { // singleton descendant public: bool isSingleton(void) { return true; } } class Second : public Base { // normal descendant public: bool isSingleton(void) { return false; } } Base *Base::New(void) { if (isSingleton()) if (Instance != NULL) return Instance = new /* descendant constructor */; else return Instance; else return new /* descendant constructor */; } Arising problems: how to declare static variable Instance, so it would be static in descendant classes how to call descendant constructors in base class I reckon it might be impossible to overcome these problems the way I planned it. If so, I'd like some advice on how to solve it in any other way. Edit: some minor changes in code. I have missed few pointer marks in it.
Just to check we have our terminologies in synch - in my book, a factory class is a class instances of which can create instances of some other class or classes. The choice of which type of instance to create is based on the inputs the factory receives, or at least on something it can inspect. Heres's a very simple factory: class A { ~virtual A() {} }; class B : public A {}; class C : public A {}; class AFactory { public: A * Make( char c ) { if ( c == 'B' ) { return new B; } else if ( c == 'C' ) { return new C; } else { throw "bad type"; } } }; If I were you I would start again, bearing this example and the following in mind: factorioes do not have to be singletons factories do not have to be static members factories do not have to be members of the base class for the hierarchies they create factory methods normally return a dynamically created object factory methods normally return a pointer factory methods need a way of deciding which class to create an instance of I don't see why your factory needs reflection, which C++ does not in any case support in a meaningful way.
959,261
959,282
My C Program provides a callback function for a hook. How can I keep it alive, un-kludgily?
Currently, I'm spawning a message box with a OS-library function (Windows.h), which magically keeps my program alive and responding to calls to the callback function. What alternative approach could be used to silently let the program run forever? Trapping 'Ctrl-c' or SIGINT and subsequently calling RemoveHook() for a clean exit would be nice to have but is not essential. HOOK my_hook; CALLBACK my_callback_fn() { ... } int main() { my_hook = SetHook(my_callback_fn); MessageBox("Press OK to stop."); // This is bad. RemoveHook(my_hook); return 0; }
You probably want to pump messages. A typical message loop looks like something like this: BOOl ret; MSG msg; while ((ret=::GetMessage(&msg, hWnd, 0, 0))!=0) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } You don't seem to have an actual window to pump on, and you don't say what SetHook is actually doing - maybe that will be able to provide one for you? Another method is to use the MsgWait functions. Maybe you have some kind of handle that you are waiting to become signalled so you can exit?: while (::MsgWaitForMultipleObjects(1, &handle, FALSE, INFINITE, QS_ALLEVENTS)==WAIT_OBJECT_0+1+ { BOOl ret; MSG msg; while ((ret=::PeekMessage(&msg, hWnd, 0, 0, TRUE))!=0) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } }
959,589
959,594
Is there any Win32 API to trigger the hibernate or suspend mode in Windows?
Is there any Win32 API to put the machine into hibernate or suspend mode? I read MSDN and found that WM_POWERBROADCAST message gets broadcasted when power-management events occur. I thought of simulating the same with PostMessage(WM_POWERBROADCAST). Is this the correct way of doing or any Win32 API exists to achieve this?
Check out SetSuspendState. Note that you need SE_SHUTDOWN_NAME privilege, as mentioned on the referenced msdn page.
959,621
959,631
C++ idiom to avoid memory leaks?
In the following code, there is a memory leak if Info::addPart1() is called multiple times by accident: typedef struct { }part1; typedef struct { }part2; class Info { private: part1* _ptr1; part2* _ptr2; public: Info() { _ptr1 = _ptr2 = NULL; } ~Info() { delete _ptr1; delete _ptr2; } addPart1() { _ptr1 = new part1; } addPart2() { _ptr2 = new part2; } }; Info _wrapper; _wrapper.addPart1(); _wrapper.addPart2(); Is there a C++ idiom to handle this problem ? I could rewrite addPart1 and addPart2 like this to defend the MLK addPart1() { if(_ptr1 != NULL) delete _ptr1; _ptr1 = new part1; } Is that a good solution?
Use a smart pointer such as boost:shared_ptr , boost:scoped_ptr is recommended to manage the raw pointer. auto_ptr is tricky to work with, you need pay attention to that.
959,837
959,873
How can I know the type of a file using Boost.Filesystem?
I'm using Boost but I cannot find complete (or good) documentation about the filesystem library in the installation directory nor the web. The "-ls" example I found has been quite a helper but it's not enough. Thanks in advance :)
How about: http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm The functions for figuring out the file type (directory, normal file etc.) is found on this subpage: http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/reference.html#file_status If you are looking for the file extension check out: template <class Path> typename Path::string_type extension(const Path &p); on the page: http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/reference.html#Convenience-functions
959,947
960,084
Asynchronous Windows Console input whilst outputting
I'm having issues trying to read input whilst outputting at the same time. I need a server console for my game which can receive input whilst outputting and not mess up the buffer. For example, I'm typing "Hello world" and in the process, player deaths, kills, etc. are being outputted into the console, which would result in something like: Hello *Player killed Player2*world Thanks in advance
Instead of writing output directly to the console, why not spawn a GUI window? Then, just have one area where output is directed, and a separate input area at the bottom where you can type commands. Kinda like how an irc client would look. If it has to be console only, I would suggest using something like ncurses (or PDCurses) to create a text based interface.
959,951
959,972
Returning reference to static local variable in C++
This question is just for my better understanding of static variables in C++. I thought I could return a reference to a local variable in C++ if it was declared static since the variable should live-on after the function returns. Why doesn't this work? #include <stdio.h> char* illegal() { char * word = "hello" ; return word ; } char* alsoNotLegal() { static char * word = "why am I not legal?" ; return word ; } int main() { // I know this is illegal //char * ill = illegal(); //ill[ 0 ] = '5' ; //puts( ill ) ; // but why is this? I thought the static variable should "live on" forever - char * leg = alsoNotLegal() ; leg[ 0 ] = '5' ; puts( leg ) ; }
The two functions are not itself illegal. First, you in both case return a copy of a pointer, which points to an object having static storage duration: The string literal will live, during the whole program duration. But your main function is all about undefined behavior. You are not allowed to write into a string literal's memory :) What your main function does can be cut down to equivalent behavior "hello"[0] = '5'; "why am I not legal?"[0] = '5'; Both are undefined behavior and on some platforms crash (good!). Edit: Note that string literals have a const type in C++ (not so in C): char const[N]. Your assignment to a pointer to a non-const character triggers a deprecated conversion (which a good implementation will warn about, anyway). Because the above writings to that const array won't trigger that conversion, the code will mis-compile. Really, your code is doing this ((char*)"hello")[0] = '5'; ((char*)"why am I not legal?")[0] = '5'; Read C++ strings: [] vs *
960,036
960,038
How to change a value in memory space of another process
If you could help me with this dilemma I have. Now, I know C \ C++, I know asm, I know about dll injection, I know about virtual memory addressing, but I just can't figure out how software like CheatEngine, and others, manage to change a variable's value in another process. For those who don't know, 3rd party cheat engine tools can scan for values in the memory space of a program and identify the location of a variable with a given value and change it. My question is, how do they do it? Given an address, if I were to write C code, how could I change the value at that address belonging to another process without getting an invalid addressing error? Thanks.
I'm fairly certain those programs are pretending to be debuggers. On Windows, I would start with DebugActiveProcess() and go from there. Oh, and the very useful looking ReadProcessMemory() function (and WriteProcessMemory()).
960,089
963,913
Html renderer with limited resources (good memory management)
I'm creating a linux program in C++ for a portable device in order to render html files. The problem is that the device is limited in RAM, thus making it impossible to open big files (with actual software). One solution is to dynamically load/unload parts of the file, but I'm not sure how to implement that. The ability of scrolling is a must, with a smooth experience if possible I would like to hear from you what is the best approach for such situation ? You can suggest an algorithm, an open-source project to take a look at, or a library that support what I'm trying to do (webkit?). EDIT: I'm writing an ebook reader, so I just need pure html rendering, no javascript, no CSS, ...
To be able to browse a tree document (like HTML) without fully loading, you'll have to make a few assumptions - like the document being an actual tree. So, don't bother checking close tags. Close tags are designed for human consumption anyway, computers would be happy with <> too. The first step is to assume that the first part of your document is represented by the first part of your document. That sounds like a tautology, but with "modern" HTML and certainly JS this is technically no longer true. Still, if any line of HTML can affect any pixel, you simply cannot partially load a page. So, if there's a simple relation between position the the HTML file and pages on screen, the next step is to define the parse state at the end of each page. This will then include a single file offset, probably (but not necessarily) at the end of a paragraph. Also part of this state is a stack of open tags. To make paging easier, it's smart to keep this "page boundary" state for each page you've encountered so far. This makes paging back easy. Now, when rendering a new page, the previous page boundary state will give you the initial rendering state. You simply read HTML and render it element by element until you overflow a single page. You then backtrack a bit and determine the new page boundary state. Smooth scrolling is basically a matter of rendering two adjacent pages and showing x% of the first and 100-x% of the second. Once you've implemented this bit, it may become smart to finish a paragraph when rendering each page. This will give you slightly different page lengths, but you don't have to deal with broken paragraphs, and that in turn makes your page boundary state a bit smaller.
960,122
961,130
Xerces-C problems; segfault on call to object destructor
I've been playing around with the Xerces-C XML library. I have this simple example I'm playing with. I can't seem to get it to run without leaking memory and without segfaulting. It's one or the other. The segfault always occurs when I delete the parser object under "Clean up". I've tried using both the 2.8 & 2.7 versions of the library. Note: I took all of the exception checking out of the code, I get the same results with it and without it. For readability and simplicity I removed it from the code below. Any Xerces-savvy people out there care to make some suggestions? I can't really tell much from the back trace, it's just jumping down into the superclass destructor and segfaulting there. Backtrace: (gdb) bt #0 0x9618ae42 in __kill () #1 0x9618ae34 in kill$UNIX2003 () #2 0x961fd23a in raise () #3 0x96209679 in abort () #4 0x95c5c005 in __gnu_cxx::__verbose_terminate_handler () #5 0x95c5a10c in __gxx_personality_v0 () #6 0x95c5a14b in std::terminate () #7 0x95c5a6da in __cxa_pure_virtual () #8 0x003e923e in xercesc_2_8::AbstractDOMParser::cleanUp () #9 0x003ead2a in xercesc_2_8::AbstractDOMParser::~AbstractDOMParser () #10 0x0057022d in xercesc_2_8::XercesDOMParser::~XercesDOMParser () #11 0x000026c9 in main (argc=2, argv=0xbffff460) at test.C:77 The code: #include <string> #include <vector> #if defined(XERCES_NEW_IOSTREAMS) #include <iostream> #else #include <iostream.h> #endif #include <xercesc/dom/DOM.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMElement.hpp> #include <xercesc/dom/DOMImplementation.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/sax/HandlerBase.hpp> #include <xercesc/util/OutOfMemoryException.hpp> #include <xercesc/framework/MemBufInputSource.hpp> using namespace std; XERCES_CPP_NAMESPACE_USE int main(int argc, char const* argv[]) { string skXmlMetadata = "<?xml version=\"1.0\"?>\n <xmlMetadata>b</xmlMetadata>"; XMLPlatformUtils::Initialize(); XercesDOMParser* xmlParser = NULL; DOMWriter* xmlWriter = NULL; ErrorHandler* errHandler = NULL; const XMLByte* xmlBuf = NULL; MemBufInputSource* memBufIS = NULL; DOMNode* xmlDoc = NULL; xmlParser = new XercesDOMParser(); xmlParser->setValidationScheme( XercesDOMParser::Val_Never ); xmlParser->setDoNamespaces( false ); xmlParser->setDoSchema( false ); xmlParser->setLoadExternalDTD( false ); errHandler = (ErrorHandler*) new HandlerBase(); xmlParser->setErrorHandler( errHandler ); // Create buffer for current xmlMetadata xmlBuf = (const XMLByte*) skXmlMetadata.c_str(); const char* bufID = "XmlMetadata"; memBufIS = new MemBufInputSource( xmlBuf, skXmlMetadata.length(), bufID, false ); // Parse xmlParser->resetErrors(); xmlParser->parse( *memBufIS ); xmlDoc = xmlParser->getDocument(); // Write created xml to input SkArray XMLCh* metadata = NULL; xmlWriter = DOMImplementation::getImplementation()->createDOMWriter(); xmlWriter->setFeature( XMLUni::fgDOMWRTFormatPrettyPrint, true ); metadata = xmlWriter->writeToString( *xmlDoc ); xmlWriter->release(); // Print out our parsed document char* xmlMetadata = XMLString::transcode( metadata ); string c = xmlMetadata; cout << c << endl; // Clean up XMLString::release( &xmlMetadata ); xmlDoc->release(); delete xmlParser; // Dies here delete memBufIS; delete errHandler; XMLPlatformUtils::Terminate(); return 0; }
" xmlDoc->release(); " is the culprit. You dont own that Node unless you say " xmlParser->adoptDocument() " http://xerces.apache.org/xerces-c/apiDocs-2/classAbstractDOMParser.html#fe052561c37d70b62ac57ab6706d75aa
960,218
960,221
i need a good website to learn c++
i want to learn C++; and i already have a compiler. i already know a few programming languages including: BASIC (yes, the dos version) visualBasic (using VisualBasic Express 2006 or 8 i'm not quite sure) Java PHP HTML (if we count that) so it doesn't need to be for absolute beginners; although if you find one post it too.
www.cplusplus.com is a great website with tons of documentation for experts and beginners. Tutorials for beginners: http://www.cplusplus.com/doc/tutorial/ An additional website I heartily reccomend once you have a little more expertise is the C++ FAQ Lite.
960,432
960,445
UML - How to manage big class diagrams?
For my project report, i need to show the class diagram of the software i've built which counts around 20 classes! The problem, is that when i render the class diagram in jpeg file(either using StarUML or ArgoUMl or whatever..) we can't see the details correctly (very big picture because of the large number of classes). Well, how to manage this situation correctly? Since the report is gonna be printed on A4 pages ? Thanks !
With 20 classes I would expect at least 3 subsystems, (modules, layers), possibly more Make package diagram showing the relation between those, one class diagram for each subsystem. Add class diagrams for special things you want to show. Print each on A4. If you can't split the diagram easily into modules, I'd consider that a design smell. Its fun to print large diagrams on huge pieces of paper (like 500 tables on A0 ;-) but it really isn't of much use.
960,459
960,703
realloc crashing in previously stable function
Apparently this function in SDL_Mixer keeps dying, and I'm not sure why. Does anyone have any ideas? According to visual studio, the crash is caused by Windows triggering a breakpoint somewhere in the realloc() line. The code in question is from the SVN version of SDL_Mixer specifically, if that makes a difference. static void add_music_decoder(const char *decoder) { void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **)); if (ptr == NULL) { return; /* oh well, go on without it. */ } music_decoders = (const char **) ptr; music_decoders[num_decoders++] = decoder; } I'm using Visual Studio 2008, and music_decoders and num_decoders are both correct (music_decoders contains one pointer, to the string "WAVE", and music_decoders. ptr is 0x00000000, and the best I can tell, the crash seems to be in the realloc() function. Does anyone have any idea how I could handle this crash problem? I don't mind having to do a bit of refactoring in order to make this work, if it comes down to that.
For one thing, it's not valid to allocate an array of num_decoders pointers, and then write to index num_decoders in that array. Presumably the first time this function was called, it allocated 0 bytes and wrote a pointer to the result. This could have corrupted the memory allocator's structures, resulting in a crash/breakpoint when realloc is called. Btw, if you report the bug, note that add_chunk_decoder (in mixer.c) is broken in the same way. I'd replace void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **)); with void *ptr = realloc(music_decoders, (num_decoders + 1) * sizeof(*music_decoders));
960,541
960,570
Detecting reason for failure to open an ofstream when fail() is true
Seems like this should be simple, but I don't find it in a net search. I have an ofstream which is open(), and fail() is now true. I'd like to know the reason for the failure to open, like with errno I would do sys_errlist[errno].
Unfortunately, there is no standard way of finding out exactly why open() failed. Note that sys_errlist is not standard C++ (or Standard C, I believe).
960,648
961,183
Calculating larger values of the ackermann function
I have some code: int CalculateAckermann(int x, int y) { if(!x) { return y++; } if(!y) { return CalculateAckermann(x--,1); } else { return CalculateAckermann(x--, CalculateAckermann(x, y--)); } } Designed to calculate the ackermann function. Above a fairly low number of x and y the application causes a stack overflow because it recurses too deeply and results in pretty big numbers. How would I go about slowly calculating a solution?
As a note if you wish to just used the closed form, then the algorithms for m<4 are straightforward. If you wish to extend to tetration, then I suggest you write a fastpower algorithm probably using the binary method and then with that method you can write a tetration function. Which would look something like: int Tetration(int number, int tetrate) { long int product=1; if(tetrate==0) return product; product=number; while(tetrate>1) { product=FastPower(number,product); tetrate--; } return product; } Then you can cover cases up to n==4 and after that use the recursive definition and values of A(5,n) overflow at a ridiculous rate, so it's really of no concern. Although your teacher probably won't be satisfied with an algorithm such as this, but it will run much faster. In one of my discrete classes when I asked to write an algorithm to compute the fibonacci numbers and then find its O(n), I wrote the closed form and then wrote O(1) and got full credit, some professors appreciate clever answers. What is important to note about the Ackerman function is it essentially defines the heirachy of additive functions on the integers, A(1,n) is addition , A(2,n) is multiplication, A(3,n) is exponentiation, A(4,n) is tetration and after 5 the functions grow too fast to be applicable to very much. Another way to look at addition, multiplication, etc is: Φ0 (x, y ) = y + 1 Φ1 (x, y ) = +(x, y ) Φ2 (x, y ) = ×(x, y ) Φ3 (x, y ) = ↑ (x, y ) Φ4 (x, y ) = ↑↑ (x, y ) = Φ4 (x, 0) = 1 if y = 0 = Φ4 (x, y + 1) = Φ3 (x, Φ4 (x, y )) for y > 0 (Uses prefix notation ie +(x,y)=x+y, (x,y)=xy.
961,237
961,396
When to use assembly language to debug a c/c++ program?
When to use the assembly to debug a c/c++ program? Does it help to learn some assembly to debug programs?
It can be very helpful in cases where you can not (yet) reliably reproduce a bug, such as due to heap/stack corruption. You might get one or two core dumps, quite possibly from a customer. Even assuming your debugger is reliable, looking at assembly can tell you exactly which instruction is crashing (and thus which piece of memory is corrupted). Furthermore, in my experience (primarily in kernel debugging) the debuggers have been relatively bad at dealing with optimized code. They get things like parameters/etc wrong, and to really tell what's going on I need to look at diassembly. If I can reproduce a problem reliably/easily it doesn't tend to be as helpful to deal with disassembly, because I'll get more information from just stepping through the program. On the other hand, getting to the point where you can reproduce a problem is usually more than halfway to fixing it.
961,297
961,311
Does defensive programming violate the DRY principle?
Disclaimer: I am a layperson currently learning to program. Never been part of a project, nor written anything longer than ~500 lines. My question is: does defensive programming violate the Don't Repeat Yourself principle? Assuming my definition of defensive programming is correct (having the calling function validate input instead of the opposite), wouldn't that be detrimental to your code? For instance, is this bad: int foo(int bar) { if (bar != /*condition*/) { //code, assert, return, etc. } } int main() { int input = 10; foo(input); //doesn't the extra logic foo(input); //and potentially extra calls foo(input); //work against you? } compared to this: int main() { if (input == /*condition*/) { foo(input); foo(input); foo(input); } } Again, as a layperson, I don't know how much simple logic statements count against you as far as performance goes, but surely defensive programming is not good for the program or the soul.
It all comes down to the contract the interface provides. There are two different scenarios for this: inputs and outputs. Inputs--and by that I basically mean parameters to functions--should be checked by the implementation as a general rule. Outputs--being return results--should be basically trusted by the caller, at least in my opinion. All of this is tempered by this question: what happens if one party breaks the contract? For example, lets say you had an interface: class A { public: const char *get_stuff(); } and that contract specifies that a null string will never be returned (it'll be an empty string at worst) then it's safe to do this: A a = ... char buf[1000]; strcpy(buf, a.get_stuff()); Why? Well, if you're wrong and the callee returns a null then the program will crash. That's actually OK. If some object violates its contract then generally speaking the result should be catastrophic. The risk you face in being overly defensive is that you write lots of unnecessary code (which can introduce more bugs) or that you might actually mask a serious problem by swallowing an exception that you really shouldn't. Of course circumstances can change this.
961,565
987,185
Xerces: How to merge duplicate nodes?
My question is this: If I have the following XML: <root> <alpha one="start"> <in>1</in> </alpha> </root> and then I'll add the following path: <root><alpha one="start"><out>2</out></alpha></root> which results in <root> <alpha one="start"> <in>1</in> </alpha> </root> <root> <alpha one="start"> <out>2</out> </alpha> </root> I want to be able to convert it into this: <root> <alpha one="start"> <in>1</in> <out>2</out> </alpha> </root> Besides implementing it myself (don't feel like reinventing the wheel today), is there a specific way in Xerces (2.8,C++) to do it? If so, at which point of the DOMDocuments life is the node merging done? at each insertion? at the writing of the document, explicitly on demand? Thanks.
If you use xalan its possible to use an xpath to find the element and directly insert into the correc one. The following code may be slow but returns all "root" elments with the attribute "one" set to "start". selectNodes("//root[@one="start"]") It is probably better to use the full path selectNodes("/abc/def/.../root[@one="start"]") or if you already have the parent element work relative selectNodes("./root[@one="start"]") I think to get the basic concepts xpath on wikipedia.
961,943
961,947
c++ overloading operators, assignment, deep-copy and addition
I'm doing some exploration of operator-overloading at the moment whilst re-reading some of my old University text-books and I think I'm mis-understanding something, so hopefully this will be some nice easy reputation for some answerers. If this is a duplicate please point me in the right direction. I've created a simple counter class that has (at this stage) a single member, val (an int). I have initialised three of these counters, varOne to varThree, and want the third counter to be the sum of the first two (e.g. varThree.val is set to 5 in the below code) counter::counter(int initialVal) { val = initialVal; //pVal = new int; //*pVal = 10; // an arbitrary number for now } int main (int argc, char const* argv[]) { counter varOne(3), varTwo(2), varThree; varThree = varOne + varTwo; return 0; } I've overloaded operator+ like so: counter operator+(counter& lhs, counter& rhs) { counter temp(lhs.val + rhs.val); return temp; } I've made this a non-member function, and a friend of the counter class so that it can access the private values. My problem starts when adding another private member, pVal (a pointer to an int). Adding this means that I can no longer do a simple varThree = varOne copy because when varOne is destroyed, varThree.pVal will still be pointing to the same bit of memory. I've overloaded operator= as follows. int counter::getN() { return *newVal; } counter& counter::operator=(counter &rhs) { if (this == &rhs) return *this; val = rhs.val; delete pVal; pVal = new int; *pVal = rhs.getN(); return *this; } Now if I do something like varThree = varOne everything copies correctly, however trying to do varThree = varOne + varTwo gives me the following error: counter.cpp: In function ‘int main(int, const char**)’: counter.cpp:96: error: no match for ‘operator=’ in ‘varThree = operator+(counter&, counter&)(((counter&)(& varTwo)))’ counter.cpp:55: note: candidates are: counter& counter::operator=(counter&) make: *** [counter] Error 1 It looks as though counter::operator= is having trouble coping with the return output from operator+, and that I need to overload operator= further to accept the type that operator+ is returning, but I've had no luck and I'm beginning to think that maybe I've done something fundamentally wrong.
You need to pass your parameters as const reference. For example: counter& counter::operator=( const counter &rhs ) And similarly for operator+(). This is necessary in order to be able to bind temporary values to the function parameter(s). Temporary values are created when you return by value, so when you say: varOne + varTwo a nameless temporary is created. This is the right thing to do, but you have to make sure that functions such as the assignment op can accept such values by making their parameters const. You also need to implement the copy constructor and destructor for your class, though lack of these will not cause compilation errors (unfortunately).
961,970
961,998
Flash SMS in Windows Mobile
How can i write code for send Flash SMS (Sms Class 0) in Windows Mobile? please guide me with .NET or C++ code also .Net is better.
Use the PROVIDER_SPECIFIC_MESSAGE_CLASS enumeration's PS_MESSAGE_CLASS0 value provided in a call to SmsSendMessage (the pbProviderSpecificData parameter). This code is a bit lower level than Compact Framework's APIs, thus gives you some more control over the message you want to send. You have to marshall it from native DLL. Here's an example of using it in Compact Framework.
962,086
962,094
One question about element inserting in STL list
CODE: struct Stringdata { // Length of data in buffer. size_t len; // Allocated size of buffer. size_t alc; // Buffer. char data[1]; }; typedef std::list<Stringdata*> Stringdata_list; Stringdata_list strings_; Stringdata *psd = this->strings_.front(); //... if (len > psd->alc - psd->len) alc = sizeof(Stringdata) + buffer_size; else { char* ret = psd->data + psd->len; memcpy(ret, s, len - sizeof(Stringpool_char)); memset(ret + len - sizeof(Stringpool_char), 0, sizeof(Stringpool_char)); psd->len += len; return reinterpret_cast<const Stringpool_char*>(ret); } In the code sample above, I have confused about the operations in the else branch. Does it create a new element and insert it after the front element or just place a new element after within the first element of list?
Your code appears to do neither. The code in the else branch does not modify the strings_ structure at all. The code is only modifying the element return from the front of the list. This should have no affect on the actual list structure.
962,132
962,148
Calling virtual functions inside constructors
Suppose I have two C++ classes: class A { public: A() { fn(); } virtual void fn() { _n = 1; } int getn() { return _n; } protected: int _n; }; class B : public A { public: B() : A() {} virtual void fn() { _n = 2; } }; If I write the following code: int main() { B b; int n = b.getn(); } One might expect that n is set to 2. It turns out that n is set to 1. Why?
Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further. The C++ FAQ Lite covers this in section 23.7 in pretty good detail. I suggest reading that (and the rest of the FAQ) for a followup. Excerpt: [...] In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. Objects are constructed from the base up, “base before derived”. [...] Destruction is done “derived class before base class”, so virtual functions behave as in constructors: Only the local definitions are used – and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object. EDIT Corrected Most to All (thanks litb)
962,175
975,835
Compiling with Ogre + MFC in _DEBUG mode
There is a problem compiling Ogre with MFC in debug mode, you get an error because of the MFC macro: #ifdef _DEBUG #define new DEBUG_NEW Which basically clobbers Ogre's debug new - #define OGRE_NEW new (__FILE__, __LINE__, __FUNCTION__) I'm trying to get MFC+Ogre to run merrily together in DEBUG mode, and I got it to compile with: #ifdef _DEBUG #undef new #endif Ogre::Root * root = OGRE_NEW Ogre::Root( pluginsFile, "ogre.cfg", "Ogre.log" ); #ifdef _DEBUG #define new DEBUG_NEW #endif But now, I get a runtime error: Ogre::InternalErrorException Anybody else face/solve this problem?
I think this might be a problem in the specific machine I was using. I tried this out on another machine, and it seemed to work in debug mode with the #ifdefs #undefs as shown above.
962,573
962,595
How to manipulate this interface?
I have seen lots of kinds of interface to multithreading and locks. These make me feel frustrating, Some of them include 2 different classes like the sample below, while others have only one class and the acquire() can implement the wait function. My questions are: Why we design locks like this in object oriented programming? How to manipulate such objects? class Lock { public: Lock(); ~Lock(); // Acquire the lock. void acquire() { this->lock_->acquire(); } // Release the lock. void release() { this->lock_->release(); } private: // This class can not be copied. Lock(const Lock&); Lock& operator=(const Lock&); friend class Condvar; Lock_impl* get_impl() const { return this->lock_; } Lock_impl* lock_; }; class Condvar { public: Condvar(Lock& lock); ~Condvar(); // Wait for the condition variable to be signalled. This should // only be called when the lock is held. void wait() { this->condvar_->wait(this->lock_.get_impl()); } // Signal the condition variable--wake up at least one thread // waiting on the condition variable. This should only be called // when the lock is held. void signal() { this->condvar_->signal(); } // Broadcast the condition variable--wake up all threads waiting on // the condition variable. This should only be called when the lock // is held. void broadcast() { this->condvar_->broadcast(); } private: // This class can not be copied. Condvar(const Condvar&); Condvar& operator=(const Condvar&); Lock& lock_; Condvar_impl* condvar_; };
The above is a lock and a condition variable. These are two unique concepts: A lock is just a single atomic lock on or off. A condition variable (is much harder to use correctly) and requires a lock to implement correctly but maintains a state (basically a count). For information about "Condition Variables" see: http://en.wikipedia.org/wiki/Monitor_(synchronization) Basically condition variables are low level primitives used to create "Monitor" (aka Monitor Regions). Monitors are regions of code designed to be used by multiple threads (but usually a controlled number (in simple cases one)) but still be multi-thread safe. The following provides a good example of using a 'Condition Variable'. How to implement blocking read using POSIX threads Basically 2 threads are allowed into to the Monitor area. A thread is reading from a vector while a second threads is witting from the vector. The 'Monitor' controls the interaction between the 2 threads. Though the same effect can be achieved using just locks it is much/much/much harder to do correctly.
962,590
962,606
Constructor cannot access private members of its own class
I get the following error in Visual Studio 2008: error C2248: 'Town::Town' : cannot access private member declared in class 'Town'. It looks like the constructor is unable to access the members of its own class. Any idea what's going on? Here's the code: I have this: template<class T> class Tree{...} And this class: class Town{ Town(int number):number(number){}; ... private: int number; }; Which is used in this class: class Country{ public: StatusType AddTown(Shore side, int location, int maxNeighborhoods); private: Tree<Town> towns[2]; ... } And here's the AddTown function: StatusType Country::AddTown(Shore side, int location, int maxNeighborhoods){ if (maxNeighborhoods<0 || location<0){ return INVALID_INPUT; } Town* dummy= new Town(location);//Here be error C2248 if (towns[side].find(*dummy)!=NULL){ delete dummy; return FAILURE; } SouthBorder* dummyBorder; (side==NORTH)?dummyBorder=new SouthBorder(location,0):dummyBorder=new SouthBorder(0,location); if (southBorders.find(*dummyBorder)!=NULL){ delete dummyBorder; return FAILURE; } towns[side].add(*dummy); delete dummyBorder; return SUCCESS; }
By default class access level is private. If you do not add a public: before the Town constructor it will be private. class Town{ public: // <- add this Town(int number):number(number){}; ... private: int number; };
962,599
962,650
Binary operator overloading on a templated class
I was recently trying to gauge my operator overloading/template abilities and as a small test, created the Container class below. While this code compiles fine and works correctly under MSVC 2008 (displays 11), both MinGW/GCC and Comeau choke on the operator+ overload. As I trust them more than MSVC, I'm trying to figure out what I'm doing wrong. Here is the code: #include <iostream> using namespace std; template <typename T> class Container { friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs); public: void setobj(T ob); T getobj(); private: T obj; }; template <typename T> void Container<T>::setobj(T ob) { obj = ob; } template <typename T> T Container<T>::getobj() { return obj; } template <typename T> Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) { Container<T> temp; temp.obj = lhs.obj + rhs.obj; return temp; } int main() { Container<int> a, b; a.setobj(5); b.setobj(6); Container<int> c = a + b; cout << c.getobj() << endl; return 0; } This is the error Comeau gives: Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions "ComeauTest.c", line 27: error: an explicit template argument list is not allowed on this declaration Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) ^ 1 error detected in the compilation of "ComeauTest.c". I'm having a hard time trying to get Comeau/MingGW to play ball, so that's where I turn to you guys. It's been a long time since my brain has melted this much under the weight of C++ syntax, so I feel a little embarrassed ;). EDIT: Eliminated an (irrelevant) lvalue error listed in initial Comeau dump.
I found the solution thanks to this forum posting. Essentially, you need to have a function prototype before you can use 'friend' on it within the class, however you also need the class to be declared in order to properly define the function prototype. Therefore, the solution is to have two prototype definitons (of the function and the class) at the top. The following code compiles under all three compilers: #include <iostream> using namespace std; //added lines below template<typename T> class Container; template<typename T> Container<T> operator+ (Container<T>& lhs, Container<T>& rhs); template <typename T> class Container { friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs); public: void setobj(T ob); T getobj(); private: T obj; }; template <typename T> void Container<T>::setobj(T ob) { obj = ob; } template <typename T> T Container<T>::getobj() { return obj; } template <typename T> Container<T> operator+ (Container<T>& lhs, Container<T>& rhs) { Container<T> temp; temp.obj = lhs.obj + rhs.obj; return temp; } int main() { Container<int> a, b; a.setobj(5); b.setobj(6); Container<int> c = a + b; cout << c.getobj() << endl; return 0; }
962,879
962,895
Visual C++ Linking LNK2019 Error with a Precompiled Header
I had a very weird problem with precompile header. The linker generates LNK2019: unresolved external symbol error when I implement method in .cpp file. However, the program could be compiled if I implement method in .h file. I happened to find out a solution but I have no idea about the root cause of this error. My project structure looks like this Solution ->project 1 ->project 2 Project 1 has 3 files. A.h, A.cpp and stdafx.h file A.h #pragma once class A { public: int num; A(); }; file A.cpp #include "stdafx.h" A::A() { num = 2; } file stdafx.h ... #include "A.h" ... In project 2. I want to use A class. file whatever.cpp #include "stdafx.h" #include "../Project1/A.h" ... A* a_obj = new A(); ... In compile time, the linker reports unresolved external symbol error for the A construction function. If I implement the constructor in A.h file. the project2 could be successful complied. I want to know, why can not put the implementation in A.cpp file? What is the right way to organize precompile header? Thank you
Project 2 does not include the definition of the A constructor - one way to give it visibility of this is to include the definition in the header file (which you did). Another way would be to include the A.cpp file in project 2. A third way would be to export the A class, or the A constructor using a .def file or using the dllexport directive. Put this in the precompiled header file: // set up export import macros for client project use // define the symbol "PROJ1" before including this file in project 1 only // leave it undefined for other projects #ifdef PROJ1 #define DLLEXP __declspec(dllexport) #else #define DLLEXP __declspec(dllimport) #endif Then declare the A class in the A header: DLLEXP class A { public: A(); ... }; Or: class A { public: DLLEXP A(); ... };
962,901
962,916
End of Line on Windows cmd
I have a while(cin >> string) loop in which I want the user to input a string. However, I do not know how to end the input. I know on *nix machines for bash shell, I can use ctrl-D. But this does not seem to work on cmd.exe for Windows... Any tips? [Edit] This is on C++
The Windows equivalent of Ctrl+D is Ctrl+Z Enter.
962,925
962,927
C++ Class Common String Constants
In C++ I would like to define some strings that will be used within a class but the values will be common over all instances. In C I would have used #defines. Here is an attempt at it: #include <string> class AskBase { public: AskBase(){} private: static std::string const c_REQ_ROOT = "^Z"; static std::string const c_REQ_PREVIOUS = "^"; static std::string const c_REQ_VERSION = "?v"; static std::string const c_REQ_HELP = "?"; static std::string const c_HELP_MSG = " ? - Help\n ?v - Version\n ^^ - Root\n ^ - Previous\n ^Z - Exit"; }; int main(){AskBase a,b;} If C++0x is needed that is acceptable.
You will have to define them separately in a single translation unit (source file), like so: //header class SomeClass { static const std::string someString; }; //source const std::string SomeClass::someString = "value"; I believe the new C++1x standard will fix this, though I'm not entirely sure.
962,941
962,943
Holding cmd.exe open on Vista
I'm writing C++ console programs. After compilation, when I run the program from my file browser, cmd.exe automatically closes such that I can't see my programs output. The only way to work around this I've found is to run the program from inside cmd.exe Is there anyway to keep cmd.exe open after a program finishes running? Is there a setting I can change somewhere? I don't want to run a batch script with cmd.exe /K Thanks! [Edit] Don't know if this matters, but I'm on Vista x64
Have your application ask for a keypress before exiting - that's the easiest fix!
962,995
963,048
mapping of a contained struct with boost
Considering these two structs: struct point { int x,y; }; struct pinfo { struct point p; unsigned long flags; }; And a function, that changes a point: void p_map(struct point &p); Is it possible to use boost (e.g. boost::bind or boost::lambda) to create a function equivalent with: void pi_map(struct pinfo &pi) { p_map(pi.p); } -edit: update for additional information: The original intention for this function was to use it in for_each. For example given this function: void p_map(struct point &p) { p.x += 1; p.y += 1; } I could write: void foreach(std::vector<struct pinfo> &pi_vec) { for_each(pi_vec.begin(), pi_vec.end(), pi_map); } As it was suggested in an answer, it is possible to bound member variables with boost::lambda, and to create an alternative for_each version: void foreach2(std::vector<struct pinfo> &pi_vec) { boost::function<void (pinfo&)> pi_map2 = bind(&p_map, bind(&pinfo::p, _1)); for_each(pi_vec.begin(), pi_vec.end(), pi_map2); } My issue with this approach, is that it gcc (v. 4.3.2) does not inline the pi_map and p_map functions for the foreach2 version. The x86 code generated for the foreach1 function is: 0000000000400dd0 <foreach(std::vector<pinfo, std::allocator<pinfo> >&)>: 400dd0: 48 8b 57 08 mov 0x8(%rdi),%rdx 400dd4: 48 8b 07 mov (%rdi),%rax 400dd7: 48 39 c2 cmp %rax,%rdx 400dda: 74 14 je 400df0 <foreach(std::vector<pinfo, std::allocator<pinfo> >&)+0x20> 400ddc: 0f 1f 40 00 nopl 0x0(%rax) 400de0: 83 00 01 addl $0x1,(%rax) 400de3: 83 40 04 01 addl $0x1,0x4(%rax) 400de7: 48 83 c0 10 add $0x10,%rax 400deb: 48 39 c2 cmp %rax,%rdx 400dee: 75 f0 jne 400de0 <foreach(std::vector<pinfo, std::allocator<pinfo> >&)+0x10> 400df0: f3 c3 repz retq Which implements the for_each, without calling any functions. On the other hand, the code generated for the foreach2 is more complicated, due to optimizations, and does not (seem to) inline the mapping functions. However, this issue seems to be a philosophical, rather than a practical one with modern desktop processors, since (strangely enough) the performance on my machine is similar for both versions.
You can do it with boost::lambda, member variables can be bound with bind the same way member functions are: #include <boost/function.hpp> #include <boost/lambda/bind.hpp> using namespace boost::lambda; boost::function<void (pinfo&)> pi_map = bind(&p_map, bind(&pinfo::p, _1));
963,158
964,040
Helping getting started using Boost.Test
I am trying to start unit testing. I am looking at a few C++ frameworks and want to try Boost.Test. The documentation seems very thorough, and it's a bit overwhelming, especially someone new to unit testing. So here's a situation that I want: Let's say I have 2 classes, Foo and Bar. I want to write a suite of tests for Foo and a suite of tests for Bar, preferably in different files. I want to run the tests only if I run the program with a command line parameter. So my main() should look something like: int main(int argc, const char* argv[]) { if (argc == 1 && strcmp(argv[0], "-test") == 0) run_all_tests(); else return program_main(argc, argv); } I think test_foo.cpp should be something like: #include "foo.hpp" #define BOOST_TEST_MODULE Foo test #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE( Foo_Test ) BOOST_AUTO_TEST_CASE( Foo1 ) { Foo f; BOOST_CHECK( f.isValid() ); } BOOST_AUTO_TEST_CASE( Foo2 ) { Foo f; BOOST_CHECK( f.baz() == 5 ); } BOOST_AUTO_TEST_SUITE_END() However, I don't know (1) what the actual command to run the tests is, and (2) how to actually tell the library that I want to run EVERY test. So, who has experience with Boost.Test? Can someone help in a detailed way? Thank you so much.
BOOST.Test is very flexible and you can probably do what you want. However since you say you are new to unit testing, you should probably follow the standard unit testing structure. This is to have a separate test project for each project you are unit testing. Then include the sources and libraries you need to build the test project. This is cleaner as there are no test logic in your main project that might get run accidentally and it is easy to run the tests as they have their own executable. This approach also works for testing libraries. If you follow this structure you will find that most of the BOOST.Test defaults work out of the box and you can just worry about writing you tests and code.
963,259
963,371
Transitioning from Java to C and then C++?
Currently I am working with Java and its object oriented-design aspects (I also work with PHP/MySQL a lot). I don't implement it on the web; I just use it for designing programs for general purposes. However, now I need to learn C right now, and I have an interest in C++. I got The C Programming Language, which some people say is the best book on the subject. Can someone tell me what will be the biggest challenges, except of the String handling, in the way I think about programming design, and how I create programs? I understand that I can't have classes, but how will this impact me specifically (i.e. will I have to redesign methods and always design everything with the idea that it is harder to edit)? Also, is the jump to C++ from those languages hard? Everyone says it's a really hard language, but would some previous experience help? And with that experience would Accelerated C++ be to hard of a book to start out with? Thanks a million.
Don't worry one bit. I started programming with Java, then moved on to C++. And then I learned x86 assembly and now I'm into C and then I came back to use some features of C++ like objects. I even did a Java project not long ago. The order is not important, as long as you put work in learning these languages, you will have success with them. Now, you asked about design. I think that this is the part that you will like best. In OOP, if you wanted to create a simple wrapper over a database, you would create an Object and then you could set up an inheritance system with polymorphic functions etc. In C, you would just make a file named sqlite_wrapper.c, include #sqlite3.h and you start writing the code. You'll make a couple of functions, decide on the parameters you want to send (structures and values) and you're done. In C you don't have classes but you have FILES. Having different files already separates the logic. In Java you have files + classes inside them to separate the logic and that's also very good. Good luck, have fun.