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
453,440
453,621
COM event handling in C++
Without the following: ATL MFC Question: How to get the COM Server, to report back to the COM Client, once a particular event has terminated? Regards
See: COM event handling - IConnectionPointContainer - illustration
453,738
454,010
Inheritance or composition: Rely on "is-a" and "has-a"?
When I design classes and have to choose between inheritance and composition, I usually use the rule of thumb: if the relationship is "is-a" - use inheritance, and if the relationship is "has-a" - use composition. Is it always right? Thank you.
No - "is a" does not always lead to inheritence. A well cited example is the relationship between a square and a rectangle. A square is a rectangle, but it will be bad to design code that inherits a Square class off a Rectangle class. My suggestion is to enhance your "is a / has a" heuristic with the Liskov Substitution Principle. To check whether an inheritence relationship complies with the Liskov Substitution Principle, ask whether clients of a base class can operate on the sub class without knowing that it is operating on a sub class. Of course, all the properties of the sub class must be preserved. In the square / rectangle example, we must ask whether a client of rectangle can operate on a square without knowing that it is a square. All that the client must know is that it is operating on a rectangle. The following function demonstrates a client that assumes that setting the width of a rectangle leaves the height unchanged. void g(Rectangle& r) { r.SetWidth(5); r.SetHeight(4); assert(r.GetWidth() * r.GetHeight()) == 20); } This assumption is true for a rectangle, but not for a square. So the function cannot operate on a square and therefore the inheritence relationship violates the Liskov Substitution principle. Other examples
453,769
459,455
How do I create a Lua Table in C++, and pass it to a Lua function?
In C++, I have a map<string, string>, containing an unknown number of entries. How can I pass this to a Lua function, so that the Lua function can use the data as a table?
if you want a real lua table: lua_newtable(L); int top = lua_gettop(L); for (std::map::iterator it = mymap.begin(); it != mymap.end(); ++it) { const char* key = it->first.c_str(); const char* value = it->second.c_str(); lua_pushlstring(L, key, it->first.size()); lua_pushlstring(L, value, it->second.size()); lua_settable(L, top); } with the right types for your map substituted in..
453,928
454,276
Hibernate like layer for C++
Using a DB with C++ is a real mess and it was refreshing when I moved to Java to be able to use a unified system to abstract the whole layer away (aka Hibernate). There are a couple of C++ abstract layers for DB's out there but they are usually vendor specific and only a thin layer that wraps the real C API. Has anybody come across something more like hibernate for C++ or know of a group or open source project that is looking at this problem domain.
I don't know of any C++ library like Hibernate, but certainly there are non-vendor specific libs: SOCI and DTL
454,316
454,399
COM event notification
Without: ATL MFC Note: Client is executing in a different thread to that of the server Question: How do I control the behaviour of the client, once an event notification is received from the COM object (Server)? How to implement an event interface from client? Illustration below: hresult = pis8->QueryInterface( __uuidof(IConnectionPointContainer), (void **) &pContainer); //result handling omitted hresult = pContainer->FindConnectionPoint( __uuidof(IS8SimulationEvents), &pConnection); //result handling omitted
The client implements the event interface (IS8SimulationEvents) This can be in a separate component, or on the client component itself. The implementation is called when the component fires an event. After FindConnectionPoint, the client calls pConnection->Advise, passing the IS8SimulationEvents and receiving a "cookie". The cookie is required to call Unadvise, which must be called during cleanup to disconnect. If the client runs in a different thread than server, the client needs to run a message loop to receive calls.
454,664
454,669
Speech to text conversion in Linux
I am planning to start an application which converts the speech to text in Linux. Are there any existing interfaces so that I can extend them? or Is there any such existing application in Linux? Any inputs on this? EDIT: The application that I am planning to write should be able convert every word that we speak to text, not just the Yes/No.
Well, this is quite an undertaking and without saying what technology you want to use, here are some links: Speech Recognition on Wikipedia Java Speech API W3C Speech Recognition Grammar Specification Sphinx - An open source recognition engine written in Java Good luck. With more detail, we may be able to provide better answers. For example, there's a big difference between "yes/no" call center-style recognition vs. even partial natural language understanding.
454,762
454,782
vector or map, which one to use?
I've heard many people say that if the number of expected elements in the container is relatively small, it is better to use std::vector instead of std::map even if you were to use the container for lookups only and not iterating. What is the real reason behind this? Obviously the lookup performance of std::map cannot be worse than std::vector (although it may differ in nanoseconds/microseconds) so does it have something to do with memory usage? Does std::vector fare any better/worse than std::map in fragmenting the virtual address space? I am using the STL library that comes along with Visual Studio (i.e. Microsoft's implementation). Does that make any difference compared to other implementations?
I presume you're comparing map<A, B> with vector<pair<A, B> >. Firstly, finding an item in a very small vector can easily be faster than the same thing in a map, because all the memory in a vector is always contiguous (and so plays more nicely with computers' caches and such things), and the number of comparisons needed to find something in a vector might be about the same as for a map. Finding an element in a map needs fewer operations in the limit of very large containers. The point where maps become faster than vectors depends on the implementation, on your processor, what data is in the map, and subtle things like what memory is in the processor's cache. Typically, the point where map becomes faster would be about 5-30 elements. An alternative is to use a hash container. They are often named hash_map or unordered_map. Classes named hash_map are not part of the official standard (and there are a few variants out there); std::tr1::unordered_map is. A hash map is often faster than a normal map for lookups, regardless of how many elements are in it, but whether it is actually faster depends on what the key is, how it is hashed, what values you have to deal with, and how the key is compared in std::map. It doesn't keep things in a specific order like std::map, but you've said that you don't care about that. I'd recommend hash maps particularly if the keys are integers or pointers, because these hash very quickly.
454,811
454,845
Opening an OpenDialog from Vis C++ console app?
I know this is a darn simple question, but I'm very used to using Borland and wrappers, so this is a bit of a new approach for me. Can someone simply tell me how I Can open an OpenDialog that only gets .obj files from a visual studio c++ console app? It's very much appreciated!
There isn't really any difference between a console application and a GUI application, except for entry point (WinMain in a 'GUI' app), and a console app will have a console window opened during startup if not started from a console. All of the Win32 API is available, so you need to use the GetOpenFileName call, as follows: #define DEFAULT_EXTENSION L".obj" OPENFILENAME ofn; wchar_t *FilterSpec =L"Object Files(*.obj)\0*.obj\0Text Files(*.txt)\0*.txt\0All Files(*.*)\0*.*\0"; wchar_t *Title =L"Open...."; wchar_t szFileName[MAX_PATH]; wchar_t szFileTitle[MAX_PATH]; int Result; wchar_t filePath[MAX_PATH]; // Selected file and path *szFileName = 0; *szFileTitle = 0; /* fill in non-variant fields of OPENFILENAME struct. */ ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = GetFocus(); ofn.lpstrFilter = FilterSpec; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = 0; ofn.lpstrFile = szFileName; ofn.nMaxFile = MAX_PATH; ofn.lpstrInitialDir = L"."; // Initial directory. ofn.lpstrFileTitle = szFileTitle; ofn.nMaxFileTitle = MAX_PATH; ofn.lpstrTitle = Title; ofn.lpstrDefExt = DEFAULT_EXTENSION; ofn.Flags = OFN_FILEMUSTEXIST|OFN_HIDEREADONLY; if (!GetOpenFileName ((LPOPENFILENAME)&ofn)) { return; // Failed or cancelled } else { wcscpy_s(filePath,ofn.lpstrFile); }
454,984
455,007
Receiving COM events
Without: ATL MFC Note: Plain C++ Out-of-process COM Object/server Predefined TLB file Question: How to implement an outgoing interface, so the COM Object can notify the sink of events? How to handle the event appropriately, once received? Below is the event function I'd like to implement - from TLB file: inline HRESULT IS8SimulationEvents::S8SimulationEndRun ( ) { HRESULT _result = 0; _com_dispatch_method(this, 0x2, DISPATCH_METHOD, VT_ERROR, (void*)&_result, NULL); return _result; } Regards
Implement the source interface in COM Server class. You should implement IConnectionPointcontainer if you are not using the ATL. In the client class call the COM server as mentioned below. 1. Call FindConnectionPointContainer 2. Call FindConnectionPoint 3. Call Advise on the interface pointer returned from step 2, we should provide IUnknown pointer of sink object. Advise returns a cookie, that we can use it while calling the unadvise. To handle the events you can do it 2 ways one using the IDispatch's Invoke method to resolve the calls in Client side other is server itself calls the particular Sink method. Both the method uses the IUnknown pointer that it gets while advising.
455,125
455,162
How to implement an outgoing interface on a sink object (C++)
I have a predefined TLB file, with IS8SimulationEvents wrapper method implementations, for instance: inline HRESULT IS8SimulationEvents::S8SimulationReset ( ) { HRESULT _result = 0; _com_dispatch_method(this, 0x1, DISPATCH_METHOD, VT_ERROR, (void*)&_result, NULL); return _result; } Using Oleview, I can see the IConnectionPointContainer interface attached to the COM object. Question: How do I implement the outgoing interface on a sink object, for the client to receive event notification from the COM object Without: ATL MFC
This article explain how to implement connections points sources/sinks in plain C http://www.codeproject.com/KB/COM/com_in_c5.aspx Probably the whole series of articles "COM in plain C" by Jeff Glatt are more than recommended if you want to understand COM at the low level. PD: Lambdasoft Comet is a framework that implement COM wrappers that doesn't make use of ATL/MFC, it is pretty dated but if you want something simple it worth to take a look https://bitbucket.org/sofusmortensen/comet/ or http://www.lambdasoft.dk/comet/.
455,251
455,257
I need a slightly different multimap
I'm looking for a C++ container class, that's a lot like a multimap, but slightly different. The container would store pairs of strings. But when I retrieve items from the container using key K, I want to find all the items where K begins with the item's own key. E.G. If I use key "abcde" I want to find items with key "adc" and "abcde", but not "abcqz". Or in pseudo C++ form: multimap2<string, string> myMultiMap; myMultiMap.insert( pair("abcde", "hello")); myMultiMap.insert( pair("abc", "Hi")); myMultiMap.insert( pair("abcqz", "goodbye")); // prints 2 cout << myMultiMap.count("abcde") << endl; // prints "hello" and "Hi" cout << myMultiMap.everything_which_matches("abcde") << endl; // prints "Hi" cout << myMultiMap.everything_which_matches("abc") << endl; // prints "goodbye" cout << myMultiMap.everything_which_matches("abcqz") << endl; Insertion time is unimportant, but I need fast access to the items. Is it possible to do this with a normal Multimap by creating a special < operator? My hunch is that I would need the normal < operator for insertion, and a special one for retrieval. thanks Hugo
I would suggest using a trie. Basically you have a tree with 1 node per unique character. Your algorithm would be O(m) for both lookups and insertion, where m is the length of a string. So following your example with: "abcde", "hello" "abc", "Hi" "abcqz", "goodbye" Then you would have the following trie: a | b | c (c holds data of hi) / \ d q | | e z (z holds data of goodbye) (e holds data of hello) To do a lookup you simply start at the root node (root node not shown above), and follow the next char in your input string. Each time you reach a node that has a data result, you will include that as one of your output strings. So a search for abcde would give you: "hi", "hello" as you wanted. It would not give you "goodbye" because you did not traverse over that result node.
455,346
455,356
What to do about wrong "control reaches end of non-void function" gcc warning?
$ cat t.cpp int sign(int i) { if(i > 0) return 1; if(i == 0) return 0; if(i < 0) return -1; } $ g++ -c t.cpp -Wall t.cpp: In function ‘int sign(int)’: t.cpp:5: warning: control reaches end of non-void function $ What do I do about this? Stop using -Wall as it's clearly wrong? Add a bogus return 0 at the end? Clutter the code with "else" clauses?
If you don't want to add "else" clauses because they would make the code longer, then perhaps you would like to remove the final "if" and make the code shorter: int sign(int i) { if(i > 0) return 1; if(i == 0) return 0; return -1; // i<0 } Or if you're really computing "sign" yourself and this isn't a simplification of some longer example: int sign(int i) { return (i>0) ? 1 : ((i<0)?-1:0); }
455,434
455,533
How should I use FormatMessage() properly in C++?
Without: MFC ATL How can I use FormatMessage() to get the error text for a HRESULT? HRESULT hresult = application.CreateInstance("Excel.Application"); if (FAILED(hresult)) { // what should i put here to obtain a human-readable // description of the error? exit (hresult); }
Here's the proper way to get an error message back from the system for an HRESULT (named hresult in this case, or you can replace it with GetLastError()): LPTSTR errorText = NULL; FormatMessage( // use system message tables to retrieve error text FORMAT_MESSAGE_FROM_SYSTEM // allocate buffer on local heap for error text |FORMAT_MESSAGE_ALLOCATE_BUFFER // Important! will fail otherwise, since we're not // (and CANNOT) pass insertion parameters |FORMAT_MESSAGE_IGNORE_INSERTS, NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM hresult, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorText, // output 0, // minimum size for output buffer NULL); // arguments - see note if ( NULL != errorText ) { // ... do something with the string `errorText` - log it, display it to the user, etc. // release memory allocated by FormatMessage() LocalFree(errorText); errorText = NULL; } The key difference between this and David Hanak's answer is the use of the FORMAT_MESSAGE_IGNORE_INSERTS flag. MSDN is a bit unclear on how insertions should be used, but Raymond Chen notes that you should never use them when retrieving a system message, as you've no way of knowing which insertions the system expects. FWIW, if you're using Visual C++ you can make your life a bit easier by using the _com_error class: { _com_error error(hresult); LPCTSTR errorText = error.ErrorMessage(); // do something with the error... //automatic cleanup when error goes out of scope } Not part of MFC or ATL directly as far as I'm aware.
455,483
455,487
Going from string to stringstream to vector<int>
I've this sample program of a step that I want to implement on my application. I want to push_back the int elements on the string separately, into a vector. How can I? #include <iostream> #include <sstream> #include <vector> using namespace std; int main(){ string line = "1 2 3 4 5"; //includes spaces stringstream lineStream(line); vector<int> numbers; // how do I push_back the numbers (separately) here? // in this example I know the size of my string but in my application I won't }
int num; while (lineStream >> num) numbers.push_back(num);
455,518
455,535
How many and which are the uses of "const" in C++?
As a novice C++ programmer there are some constructs that look still very obscure to me, one of these is const. You can use it in so many places and with so many different effects that is nearly impossible for a beginner to come out alive. Will some C++ guru explain once forever the various uses and whether and/or why not to use them?
Trying to collect some uses: Binding some temporary to reference-to-const, to lengthen its lifetime. The reference can be a base - and the destructor of it doesn't need to be virtual - the right destructor is still called: ScopeGuard const& guard = MakeGuard(&cleanUpFunction); Explanation, using code: struct ScopeGuard { ~ScopeGuard() { } // not virtual }; template<typename T> struct Derived : ScopeGuard { T t; Derived(T t):t(t) { } ~Derived() { t(); // call function } }; template<typename T> Derived<T> MakeGuard(T t) { return Derived<T>(t); } This trick is used in Alexandrescu's ScopeGuard utility class. Once the temporary goes out of scope, the destructor of Derived is called correctly. The above code misses some small details, but that's the big deal with it. Use const to tell others methods won't change the logical state of this object. struct SmartPtr { int getCopies() const { return mCopiesMade; } }; Use const for copy-on-write classes, to make the compiler help you to decide when and when not you need to copy. struct MyString { char * getData() { /* copy: caller might write */ return mData; } char const* getData() const { return mData; } }; Explanation: You might want to share data when you copy something as long as the data of the originally and the copie'd object remain the same. Once one of the object changes data, you however need now two versions: One for the original, and one for the copy. That is, you copy on a write to either object, so that they now both have their own version. Using code: int main() { string const a = "1234"; string const b = a; // outputs the same address for COW strings cout << (void*)&a[0] << ", " << (void*)&b[0]; } The above snippet prints the same address on my GCC, because the used C++ library implements a copy-on-write std::string. Both strings, even though they are distinct objects, share the same memory for their string data. Making b non-const will prefer the non-const version of the operator[] and GCC will create a copy of the backing memory buffer, because we could change it and it must not affect the data of a! int main() { string const a = "1234"; string b = a; // outputs different addresses! cout << (void*)&a[0] << ", " << (void*)&b[0]; } For the copy-constructor to make copies from const objects and temporaries: struct MyClass { MyClass(MyClass const& that) { /* make copy of that */ } }; For making constants that trivially can't change double const PI = 3.1415; For passing arbitrary objects by reference instead of by value - to prevent possibly expensive or impossible by-value passing void PrintIt(Object const& obj) { // ... }
455,793
455,829
Programmatically copy a cell from Excel using VC++
Without: MFC ATL using COM, with pure C++, steps taken thus far: //steps above omitted _ApplicationPtr application(__uuidof(Excel::Application)); //omitted const BSTR wcharFileName = SysAllocString(L"..."); application->Workbooks->Open(wcharFileName); application->put_Visible(10, true); Question: How to then copy a cell, for instance A4, B4 and C4, into an array?
Try this http://support.microsoft.com/kb/216388/en-us
455,904
456,184
Print information in "test mode" but not in "normal execution"
I am using an application in c++ that uses a special dprintf function to print information, this is an example: dprintf(verbose, "The value is: %d", i); What is doing is when I define verbose for test purposes then I print the information and when I am working in normal execution I do not define it and I do not see useless information in the screen. My question is how can I do that function or implement the same idea?.
I try to avoid using var-arg c-style functions for two main reasons: They are not type-safe, can't use operator<< They don't recognize when too few or many arguments were provided I've made a way that works using boost::fusion, which is given arguments in a type-safe way. It iterates over those arguments, printing out them when a % is encountered. If too few or too many arguments were given, an exception is thrown. There is one problem still: Variadic macros are not yet standard in C++. So, i have made two versions. One that work with current C++. You have to invoke it using dprintf("name: %, value: %\n", ("foo", 42)); Then. The other version, using variadic macros, can be used by defining a preprocessor symbol, which enables you to write dprintf("name: %, value: %\n", "foo", 42); Here is the code. The boost.fusion provides more details for this: #include <boost/fusion/include/sequence.hpp> #include <boost/fusion/include/make_vector.hpp> #include <boost/fusion/include/next.hpp> #include <stdexcept> #include <iostream> template<typename IterS, typename IterSeqE> void print_vec(IterS b, IterS e, IterSeqE, IterSeqE) { while(b != e) { if(*b == '%') { if(++b != e && *b == '%') { std::cout << '%'; } else { throw std::invalid_argument("too many '%'"); } } else { std::cout << *b; } ++b; } } template<typename IterS, typename IterSeqB, typename IterSeqE> void print_vec(IterS b, IterS e, IterSeqB seqb, IterSeqE seqe) { while(b != e) { if(*b == '%') { if(++b != e && *b == '%') { std::cout << '%'; } else { std::cout << *seqb; return print_vec(b, e, next(seqb), seqe); } } else { std::cout << *b; } ++b; } throw std::invalid_argument("too few '%'"); } template<typename Seq> void print_vec(std::string const& msg, Seq const& seq) { print_vec(msg.begin(), msg.end(), begin(seq), end(seq)); } #ifdef USE_VARIADIC_MACRO # ifdef DEBUG # define dprintf(format, ...) \ print_vec(format, boost::fusion::make_vector(__VA_ARGS__)) # else # define dprintf(format, ...) # endif #else # ifdef DEBUG # define dprintf(format, args) \ print_vec(format, boost::fusion::make_vector args) # else # define dprintf(format, args) # endif #endif // test, using the compatible version. int main() { dprintf("hello %, i'm % years old\n", ("litb", 22)); }
456,303
456,312
How to validate input using scanf
How can I validate the user input by using scanf. Right now I have something like this, but doesn't work. NOTE: I have the atoi just to validate that the scanf validation works. scanf("%[0987654321.-]s",buf); i = atoi(buf); if(i) index = i;
Using scanf() is usually a bad idea for user input since failure leaves the FILE pointer at an unknown position. That's because scanf stands for "scan formatted" and there is little more unformatted than user input. I would suggest using fgets() to get a line in, followed by sscanf() on the string to actually check and process it. This also allows you to check the string for those characters you desire (either via a loop or with a regular expression), something which the scanf family of functions is not really suited for. By way of example, using scanf() with a "%d" or "%f" will stop at the first non-number character so won't catch trailing errors like "127hello", which will just give you 127. And using it with a non-bounded %s is just begging for a buffer overflow. If you really must use the [] format specifier (in scanf or sscanf), I don't think it's meant to be followed by s. And, for a robust input solution using that advice, see here. Once you have an input line as a string, you can sscanf to your hearts content.
456,310
456,339
Destructors of builtin types (int, char etc..)
In C++ the following code gives a compiler error: void destruct1 (int * item) { item->~int(); } This code is nearly the same, I just typedef the int to another type and something magic happens: typedef int myint; void destruct2 (myint * item) { item->~myint(); } Why does the second code work? Does an int get a destructor just because it has been typedefed? In case you wonder why one ever would like to do this: This comes from refactoring C++ code. We're removing the standard heap and replacing it with selfmade pools. This requires us to call placement-new and the destructors. I know that calling destructors for primitive types is useless, but we want them in the code nevertheless in case we later replace PODs with real classes. Finding out that naked int's don't work but typedefed ones do was quite a surprise. Btw - I have a solution that involves template-functions. We just typedef inside the template and everything is fine.
It's the reason that makes your code work for generic parameters. Consider a container C: template<typename T> struct C { // ... ~C() { for(size_t i = 0; i<elements; i++) buffer[i].~T(); } }; It would be annoying to introduce special cases for built-in types. So C++ allows you to do the above, even if T happens to equal to int. The holy Standard says in 12.4 p15: The notation for explicit call of a destructor can be used for any scalar type name. Allowing this makes it possible to write code without having to know if a destructor exists for a given type. The difference between using a plain int and a typedef'ed int is that they are syntactically different things. The rule is, that in a destructor call, the thing after the ~ is a type-name. int is not such a thing, but a typedef-name is. Look it up in 7.1.5.2.
456,323
456,332
Static/Dynamic Runtime Linking
What are the best practices for choosing the linking method in VC++? Can anything/everything be statically linked? On a dynamically linked project, is the relative/absolute location of the linked library important? What are the pros and cons ? added: I was mainly referring to lib files. Do they behave same as dll linking?
Dynamic links allow you to upgrade individual DLLs without recompiling your applications. That is why windows can be upgraded without your application being recompiled, because the dynamic linker is able to determine the entry points in the dll, provided that the method name exists. Statically linking your application has a benefit in that calls to the linked code are not indirected, so they run faster. This may have an impact on extremely performance dependent code. Using DLLs can also help you reduce your memory footprint, as effectively you only load the libraries as you need them and you can unload them when your done (think application plugins, only load an image browsing library when you have an image open etc.) EDIT: Robert Gamble has added a comment which I missed: DLLs are loaded into memory shared by all processes in the operating systems. This means if two programs (or two instances of your program) use the same DLL, they will use the same DLL loaded into memory which will further reduce your overall memory usage.
456,357
456,390
C++ ifstream failure, why is this line not going where it's supposed to?
I want to make the line marked with // THIS LINE SHOULD BE PRINTING do its thing, which is print the int values between "synonyms" and "antonyms". This is the text file: dictionary.txt 1 cute 2 hello 3 ugly 4 easy 5 difficult 6 tired 7 beautiful synonyms 1 7 7 1 antonyms 1 3 3 1 7 4 5 5 4 7 3 #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> using namespace std; class WordInfo{ public: WordInfo(){} ~WordInfo() { } int id() const {return myId;} void readWords(istream &in) { in>>myId>>word; } void pushSynonyms (string synline, vector <WordInfo> wordInfoVector) { stringstream synstream(synline); vector<int> synsAux; int num; while (synstream >> num) synsAux.push_back(num); for (int i=0; i<synsAux.size(); i++){ cout<<synsAux[i]<<endl; //THIS LINE SHOULD BE PRINTING } } void pushAntonyms (string antline, vector <WordInfo> wordInfoVector) { } //--dictionary output function void printWords (ostream &out) { out<<myId<< " "<<word; } //--equals operator for String bool operator == (const string &aString)const { return word ==aString; } //--less than operator bool operator <(const WordInfo &otherWordInfo) const { return word<otherWordInfo.word;} //--more than operator bool operator > (const WordInfo &otherWordInfo)const {return word>otherWordInfo.word;} private: vector <int> mySynonyms; vector <int> myAntonyms; string word; int myId; }; //--Definition of input operator for WordInfo istream & operator >>(istream &in, WordInfo &word) { word.readWords(in); } //--Definition of output operator ostream & operator <<(ostream &out, WordInfo &word) { word.printWords(out); } int main() { string wordFile; cout<<"enter name of dictionary file: "; getline (cin,wordFile); ifstream inStream (wordFile.data()); if(!inStream.is_open()) { cerr<<"cannot open "<<wordFile<<endl; exit(1); } vector <WordInfo> wordVector; WordInfo aword; while (inStream >>aword && (!(aword=="synonyms"))) { wordVector.push_back(aword); } int i=0; while (i<wordVector.size()){ cout<<wordVector[i]<<endl; i++; } vector <int> intVector; string aLine; //suspect // bad statement? while (getline(inStream, aLine)&&(aLine!=("antonyms"))){ aword.pushSynonyms(aLine, wordVector); } system("PAUSE"); return 0; }
The problem seems to be here: in>>myId>>word; On the "synonyms" line the extraction of myId fails and sets failbit on the stream, which causes the following extractions to also fail. You have to reset the error control state before extracting further elements (like the word "synonyms") from the stream: in.clear();
456,557
456,570
Getting this junk out of my vector
I want to eliminate the junk that I'm getting on the vector<int> synsAux below. It should print: 1 7 7 1 I'm getting an extra 2 before the first and third digit, why? Is this 2 an ascii value for the blank space or something? How do I avoid its reading? This is the dictionary file needed to run the program: dictionary.txt 1 cute 2 hello 3 ugly 4 easy 5 difficult 6 tired 7 beautiful synonyms 1 7 7 1 antonyms 1 3 3 1 7 4 5 5 4 7 3 #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> using namespace std; class WordInfo{ public: WordInfo(){} ~WordInfo() { } int id() const {return myId;} void readWords(istream &in) { in>>myId>>word; } void pushSynonyms (string synline, vector <WordInfo> wordInfoVector) { stringstream synstream(synline); vector<int> synsAux; int num; while (synstream >> num) synsAux.push_back(num); cout<<synsAux.size(); for (int i=0; i<synsAux.size(); i++){ cout<<synsAux[i]<<endl; // THIS LINE SHOULD BE PRINTING //1 //7 //7 //1 } } void pushAntonyms (string antline, vector <WordInfo> wordInfoVector) { } //--dictionary output function void printWords (ostream &out) { out<<myId<< " "<<word; } //--equals operator for String bool operator == (const string &aString)const { return word ==aString; } //--less than operator bool operator <(const WordInfo &otherWordInfo) const { return word<otherWordInfo.word;} //--more than operator bool operator > (const WordInfo &otherWordInfo)const {return word>otherWordInfo.word;} private: vector <int> mySynonyms; vector <int> myAntonyms; string word; int myId; }; //--Definition of input operator for WordInfo istream & operator >>(istream &in, WordInfo &word) { word.readWords(in); } //--Definition of output operator ostream & operator <<(ostream &out, WordInfo &word) { word.printWords(out); } int main() { string wordFile; cout<<"enter name of dictionary file: "; getline (cin,wordFile); ifstream inStream (wordFile.data()); if(!inStream.is_open()) { cerr<<"cannot open "<<wordFile<<endl; exit(1); } vector <WordInfo> wordVector; WordInfo aword; while (inStream >>aword && (!(aword=="synonyms"))) { wordVector.push_back(aword); } inStream.clear(); // clears failbit on the ifstream int i=0; while (i<wordVector.size()){ cout<<wordVector[i]<<endl; i++; } vector <int> intVector; string synLine; //suspect while (getline(inStream, synLine)&&(synLine!=("antonyms"))){ aword.pushSynonyms(synLine, wordVector); } system("PAUSE"); return 0; }
You're printing the twos here: cout<<synsAux.size();
456,588
456,632
mem_fun fails, pthread and class ptr
pthread takes in as its parameter void *(*start_routine)(void* userPtr), I was hoping I can use std::mem_fun to solve my problem but I cant. I would like to use the function void * threadFunc() and have the userPtr act as the class (userPtr->threadFunc()). Is there a function similar to std::mem_func that I can use?
One way is to use a global function that calls your main thread function: class MyThreadClass { public: void main(); // Your real thread function }; void thread_starter(void *arg) { reinterpret_cast<MyThreadClass*>(arg)->main(); } Then, when you want to start the thread: MyThreadClass *th = new MyThreadClass(); pthread_create(..., ..., &thread_starter, (void*)th); On the other hand, if you don't really need to use pthreads manually, it might be a good idea to have a look at Boost.Thread, a good C++ thread library. There you get classes for threads, locks, mutexes and so on and can do multi-threading in a much more object-oriented way.
456,707
456,820
How to detect launching from a "Startup"-folder shortcut?
I need to add the "Run when Windows starts" option to my program CintaNotes, but do not want to sacrifice the "cleanness" of it: it is a 100% portable freeware and should not leave traces in the system. I've come up with the idea to autodetect running from the Startup shortcut and automatically minimizing to the system tray. Is there a way to do it? I'm using C++ and raw Winapi. So: - No writing to the registry - No command line parameters Thanks! UPD: The question is NOT how to minimize to the system tray! The question is how can a program differentiate between being run normally and being run from a startup-folder shortcut without using registry and command-line parameters.
Your "cleanness" appears to be an artificial construct at best. If you're telling the user to create a shortcut in the start-up folder, you're already leaving a footprint (and, to be honest, there's little difference between "myprog.exe" and "myprog.exe -m"). In that case, there are some easier approaches than automagically trying to detect where you're running from. I would simply provide a menu option in your program ("Install") which would then install the software to a fixed-disk location (as opposed to the flash drive), including the requisite Programs entry (Start, All Programs, CintaNotes). As part of that process (or even after install), you can let them specify "Start with Windows" and then you create the start-up folder shortcut for the user with a command line option so your program can tell if it's running that way. There's no point in allowing "Start with Windows" unless the program's available (i.e., on the fixed disk, not the flash drive). Your user need never have to worry about creating shortcuts at all, let alone ones with parameters. And this gives your program the control over how it's run - two modes, "installed" (and start minimized) or "running without installing first" (and start normal). Something like finding the directory of the executable won't work simply because the start-up folder item that starts your program is likely to be a shortcut to it, so you won't have that path. I think this is a classic case of asking the wrong question. In answer to your specific question, I say: no, there is no way to tell that you've been launched from a start up folder entry without some command-line parameters. But, I've been wrong before, just ask my wife :-). Some-one else may well know a way. Adding this an an edit since comments don't allow enough space: You ask: What do you think of just disabling the "Start when Windows starts" option when program detects it is being run from the flash drive? I guess there's a way to detect this. That's a good idea since it doesn't make sense to allow automatic running until it's installed (since the flash drive may not be there). One possibility: 1/ Running from flash, you start with "myprog.exe" since you just double-clicked the executable and you run in a normal window. This presents the option to "Install to fixed disk" but not "Start with Windows". As part of the install process, you may allow them to set up the installed copy to "Start with Windows" but not the current running copy. 2/ Your installed program can be set up to run as "myprog.exe -i", since you create the item in Start/AllPrograms. This would disable "Install to fixed disk" but allow you to toggle "Start with Windows". You can choose whether you want explicit running (by the user) to start normal or minimized (see (3)). 3/ The shortcut in StartUp can be "myprog.exe -s" (again, you control this because you created it). This is identical to (2) but starts minimized (if (2) started minimized anyway, there's no distinction between (2) and (3) and no reason for different command-line options). That way, each option can have different behavior as you see fit.
456,713
456,716
Why do I get "unresolved external symbol" errors when using templates?
When I write C++ code for a class using templates and split the code between a source (CPP) file and a header (H) file, I get a whole lot of "unresolved external symbol" errors when it comes to linking the final executible, despite the object file being correctly built and included in the linking. What's happening here, and how can I fix it?
Templated classes and functions are not instantiated until they are used, typically in a separate .cpp file (e.g. the program source). When the template is used, the compiler needs the full code for that function to be able to build the correct function with the appropriate type. However, in this case the code for that function is detailed in the template's source file and hence unavailable. As a result of all this the compiler just assumes that it's defined elsewhere and only inserts the call to the templated function. When it comes to compile the template's source file, the specific template type that is being used in the program source isn't used there so it still won't generate the code required for the function. This results in the unresolved external symbol. The solutions available for this are to: include the full definition of the member function in the template's header file and not have a source file for the template, define all the member functions in the template's source file as "inline" (Update: [this does not work on Visual Studio 2017+]), or define the member functions in the template's source with the "export" keyword. Unfortunately this isn't supported by a lot of compilers. (Update: this has been removed from the standard as of C++11.) Both 1 and 2 basically address the problem by giving the compiler access to the full code for the templated function when it is attempting to build the typed function in the program source.
456,738
456,748
Should I add throw() to the declarations for my C++ destructors?
I have seen some C++ classes with a destructor defined as follows: class someClass { public: someClass(); ~someClass() throw(); }; Is this a good idea? I am well aware that destructors should never throw exceptions, but will this actually prevent me from throwing exceptions in my destructors? I'm not 100% sure what it guarantees. Reference: this recent question
It does not prevent you from throwing exceptions from your destructor. The compiler will still let you do it. The difference is that if you do allow an exception to escape from that destructor, your program will immediately call unexpected. That function calls whatever unexpected_handler points to, which by default is terminate. So unless you do something to handle an unexpected exception, your program terminates, which isn't altogether a bad idea. After all, if the exception really is unexpected, then there's not really anything your program would be able to do to handle it anyway. This isn't something special about destructors; the same rules apply to exception specifications for all methods.
456,786
456,811
Create thread with >70% CPU utilization
I am creating a test program to test the functionality of program which calcultes CPU Utilization. Now I want to test that program at different times when CPU utilization is 100%, 50% 0% etc. My question how to make CPU to utilize to 100% or may be > 80%. I think creating a while loop like will suffice while(i++< 2000) { cout<<" in while "<< endl; Sleep(10); // sleep for 10 ms. } After running this I dont get high CPU utilization. What would be the possible solutions to make high cpu intensive??
You're right to use a loop, but: You've got IO You've got a sleep Basically nothing in that loop is going to take very much CPU time compared with the time it's sleeping or waiting for IO. To kill a CPU you need to give it just CPU stuff. The only tricky bit really is making sure the C++ compiler doesn't optimise away the loop. Something like this should probably be okay: // A bit like generating a hashcode. Pretty arbitrary choice, // but simple code which would be hard for the compiler to // optimise away. int running_total = 23; for (int i=0; i < some_large_number; i++) { running_total = 37 * running_total + i; } return running_total; Note the fact that I'm returning the value out of the loop. That should stop the C++ compiler from noticing that the loop is useless (if you never used the value anywhere, the loop would have no purpose). You may want to disable inlining too, as otherwise I guess there's a possibility that a smart compiler would notice you calling the function without using the return value, and inline it to nothing. (As Suma points out in the answer, using volatile when calling the function should disable inlining.)
456,884
456,995
Extending python - to swig, not to swig or Cython
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance. With the help of swig you almost don't need to care about arguments etc. Everything works fine. Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code. Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it.
For sure you will always have a performance gain doing this by hand, but the gain will be very small compared to the effort required to do this. I don't have any figure to give you but I don't recommend this, because you will need to maintain the interface by hand, and this is not an option if your module is large! You did the right thing to chose to use a scripting language because you wanted rapid development. This way you've avoided the early optimization syndrome, and now you want to optimize bottleneck parts, great! But if you do the C/python interface by hand you will fall in the early optimization syndrome for sure. If you want something with less interface code, you can think about creating a dll from your C code, and use that library directly from python with cstruct. Consider also Cython if you want to use only python code in your program.
456,951
456,990
what is the best way to check the type of base class pointer?
I want to know the runtime type of a base class pointer, I know you can use dynamic_cast. is there any better way?
dynamic_cast will only confirm your guess, and even that is not perfect. If C inherits from B which inherits from A, dynamic_cast<B*>((A*)&theC) will work. typeid will give you the actual type, but in a way that's not quite useful for anything. You can't create new objects of that same type, for instance. So, the biq question that remains is what your real goal is. In proper OO design, you should never need to know about the unbounded set of types that can be derived from a base type.
457,040
457,144
Condition evaluation in loops?
string strLine;//not constant int index = 0; while(index < strLine.length()){//strLine is not modified}; how many times strLine.length() is evaluated do we need to put use nLength with nLength assigned to strLine.length() just before loop
length will be evaluated every time you go via the loop, however since length is constant time (O(1)) it doesn't make much difference and adding a variable for storing this value will probably have a negligible effect with a small hit on code readability (as well as breaking the code if the string is ever changed).
457,441
457,451
Does restrict help in C if a pointer is already marked const?
Just wondering: When I add restrict to a pointer, I tell the compiler that the pointer is not an alias for another pointer. Let's assume I have a function like: // Constructed example void foo (float* result, const float* a, const float* b, const size_t size) { for (size_t i = 0; i < size; ++i) { result [i] = a [0] * b [i]; } } If the compiler has to assume that result might overlap with a, it has to refetch a each time. But, as a is marked const, the compiler could also assume that a is fixed, and hence fetching it once is ok. Question is, in a situation like this, what is the recommend way to work with restrict? I surely don't want the compiler to refetch a each time, but I couldn't find good information about how restrict is supposed to work here.
Your pointer is const, telling anyone calling your function that you won't touch the data which is pointed at through that variable. Unfortunately, the compiler still won't know if result is an alias of the const pointers. You can always use a non-const pointer as a const-pointer. For example, a lot of functions take a const char (i.e. string) pointer as a parameter, but you can, if you wish, pass it a non-const pointer, the function is merely making you a promise that it wont use that particular pointer to change anything. Basically, to get closer to your question, you'd need to add restrict to a and b in order to 'promise' the compiler that whoever uses this function won't pass in result as an alias to a or b. Assuming, of course, you're able to make such a promise.
457,577
457,583
Catching access violation exceptions?
Example int *ptr; *ptr = 1000; can I catch memory access violation exception using standard C++ without using any microsoft specific.
Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.
457,595
529,725
Can you use Boost.Regex to parse a stream?
I was playing around with Boost.Regex to parse strings for words and numbers. This is what I have so far: #include <iostream> #include <string> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/range.hpp> using namespace std; using namespace boost; int main() { regex re ( "(" "([a-z]+)|" "(-?[0-9]+(\\.[0-9]+)?)" ")" ); string s = "here is a\t list of Words. and some 1239.32 numbers to 3323 parse."; sregex_iterator m1(s.begin(), s.end(), re), m2; BOOST_FOREACH (const match_results<string::const_iterator>& what, make_iterator_range(m1, m2)) { cout << ":" << what[1].str() << ":" << what.position(1) << ":" << what.length(1) << endl; } return 0; } Is there a way to tell regex to parse from a stream rather than a string? It seems like it should be possible to use any iterator.
Boost.IOStreams has a regex_filter allowing one to perform the equivalent of a regex_replace on a stream. However, looking at the implementation, it seems to "cheat" in that it simply loads the whole stream into a buffer and then calls Boost.Regex on that buffer. Making a regex search on a stream's contents without having to entirely load it in memory can be done with the "partial match" support of Boost.Regex. Look at the example at the end of the page.
457,620
457,660
Which character set to choose when compiling a c++ dll
Could someone give some info regarding the different character sets within visual studio's project properties sheets. The options are: None Unicode Multi byte I would like to make an informed decision as to which to choose. Thanks.
All new software should be Unicode enabled. For Windows apps that means the UTF-16 character set, and for pretty much everyone else UTF-8 is often the best choice. The other character set choices in Windows programming should only be used for compatibility with older apps. They do not support the same range of characters as Unicode.
457,709
458,135
VDMEnumProcessWOW returns no processes on Vista
I'm trying to use VDMEnumProcessWOW to find all 16 bit host processes on Vista. I call it, and it appears to not find any results even though I do have a 16 bit app running. I've also tried calling VDMEnumTaskWOWEx with the process id I got for ntvdm.exe from Windows Task Manager, and that also returns no results. ntvdm.exe has user name joeBlogs, and the application I've written to call VDMEnumProcessWOW is running as a service under the SYSTEM account. Is the problem that I need to have them running in the same session? EnumProcesses works ok across sessions, but is VDMEnumProcessWOW different, or is there something else I'm missing? The documentation I've seen on this so far is a little sparse. The VDM does contain the WowExec.exe task that the function's documentation says is required. Thanks.
You can request the hotfix through this link.
457,719
457,738
C++ Classes default constructor
Earlier I asked why this is considered bad: class Example { public: Example(void); ~Example(void); void f() {} } int main(void) { Example ex(); // <<<<<< what is it called to call it like this? return(0); } Now, I understand that it's creating a function prototype instead that returns a type Example. I still don't get why it would work in g++ and MS VC++ though. My next question is using the above, would this call be valid? int main(void) { Example *e = new Example(); return(0); } ? What is the difference between that and simply calling Example e()??? Like I know it's a function prototype, but it appears maybe some compilers forgive that and allow it to call the default constructor? I tried this too: class Example { private: Example(); public: ~Example(); }; int main(void) { Example e1(); // this works Example *e1 = new Example(); // this doesn't return(0); } So I'm a bit confused :( Sorry if this been asked a million times.
this question will be helpful to understand this behavior
457,896
457,963
Why is it impossible to have a reference-to-void?
Why is it impossible to have a reference to void? The only thing I found in the C++ Standard is this line, at 8.3.2.1 A declarator that specifies the type "reference to cv void" is ill-formed. Why is it that way? Why can't I write a "generic" function that accept a void&? Just to be clear, I have no useful application in mind where using a reference-to-void could be better than using templates, but I'm just curious about the rationale for forbidding this construct. To clarify a little, I understand that using a reference-to-void "as is" would be as meaningless as dereferencing a pointer-to-void. However, I could cast it to a reference-to-sometype in order to use it, couldn't I? In fact, I don't see why the following snippet can work... void foo(void *data) { int *i = reinterpret_cast<int*>(data); // do something with i } ...while this one cannot: void foo(void &data) { int &i = reinterpret_cast<int&>(data); // do something with i }
If you did have a reference to void, what would you do with it? It wouldn't be a number, or a character, or a pointer, or anything like that. Your hypothetical generic function couldn't perform any operation on it, except taking its address (and not its size). "void" has two uses: to disclaim any knowledge of type (as in void *), and to specify nothing as opposed to something (void function return). In neither case is it possible to say anything about a void something except that it may have an address. If you can't think of a way something can be useful, and I can't, that is at least evidence that something is useless, and that may well be at least part of the rationale here.
458,032
485,936
How can I add a new button to the navigation pane (outlook bar) in Outlook 2003/2007?
Most of us are familiar with the "accordion-style" navigation bar on the left side of Outlook 2003. It has buttons like Calendar, Tasks, Mail, etc, and clicking on one of those buttons opens up a browser pane with the list of common folders in that section. Using C++ or Delphi, I'd like to write a plugin that adds a new section to the navigation pane. Does anyone know where to start? I found a few postings using google that say things like, "It's impossible but if you get add-in express then it's possible" (eg. http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/a3517364-b1af-4583-966a-61717afa1028/), which sounds to me like it's possible, not impossible :) Where do I look?
This site have info for you : http://www.outlookcode.com/article.aspx?ID=36 Good look.
458,476
458,488
Best way to copy a vector to a list in STL?
Is iterating through the vector using an iterator and copying to a list the most optimal method of copying. Any recommendations?
Why would you iterate and not use the standard copy algorithm? std::copy( vector.begin(), vector.end(), std::back_inserter( list ) );
458,525
458,611
Iterating over vector and calling functions
I have a class that has a vector of another class objects as a member. In many functions of this class I have to do same operation on all the objects in the vector: class Small { public: void foo(); void bar(int x); // and many more functions }; class Big { public: void foo() { for (size_t i = 0; i < VectorOfSmalls.size(); i++) VectorOfSmalls[i]->foo(); } void bar(int x) { for (size_t i = 0; i < VectorOfSmalls.size(); i++) VectorOfSmalls[i]->bar(x); } // and many more functions private: vector<Small*> VectorOfSmalls; }; I want to simplify the code, and find a way not to duplicate going other the vector in every function. I've considered creating a function that receives a pointer to function, and calls the pointed function on every member of a vector. But I am not sure that using pointers to functions in C++ is a good idea. I have also been thinking about functors and functionoids, but it will force me to create a class per each function and it sounds like an overkill. Another possible solution is creating a function that receives a string, and calls the command according to the string: void Big::call_command(const string & command) { for (size_t i = 0; i < VectorOfSmalls.size(); i++) { if (command == "foo") VectorOfSmalls[i]->foo(); else if (command == "bar") VectorOfSmalls[i]->bar(); } } void Big::foo() { call_command("foo"); } But it might work slow (unneeded creation of a string instead of just a function call), and also creates a problem if functions have different signature. So what would you recommend? Should I leave everything the same as it is now? EDIT: I can use only STL and not boost (old compilers).
Well you can rewrite the for loops to use iterators and more of the STL like this: void foo() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::foo)); } void bar() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::bar)); } beyond that, you could use some macros to avoid retyping that a lot, but I'm not a huge fan of that. Personally, I like the multiple functions over the single one which takes a command string. As it gives you more versatility over how the decision is made. If you do go with a single function taking a param to decide which to do, I would use an enum and a switch like this, it would be more efficient than strings and a cascading if. Also, in your example you have the if to decide which to do inside the loop. It is more efficient to check outside the loop and have redundant copies of the loop since "which command" only needs to be decided once per call. (NOTE: you can make the command a template parameter if it is known at compile time, which it sounds like it is). class Big { public: enum Command { DO_FOO, DO_BAR }; void doit(Command cmd) { switch(cmd) { case DO_FOO: std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::foo)); break; case DO_BAR: std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::bar)); break; } }; Also, as you mentioned, it is fairly trivial to replace the &Small::whatever, what a member function pointer and just pass that as a parameter. You can even make it a template too. class Big { public: template<void (Small::*fn)()> void doit() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(fn)); } }; Then you can do: Big b; b.doit<&Small::foo>(); b.doit<&Small::bar>(); The nice thing about both this and the regular parameter methods is that Big doesn't need to be altered if you change small to have more routines! I think this is the preferred method. If you want to be able to handle a single parameter, you'll need to add a bind2nd too, here's a complete example: #include <algorithm> #include <functional> #include <iostream> #include <vector> class Small { public: void foo() { std::cout << "foo" << std::endl; } void bar(int x) { std::cout << "bar" << std::endl; } }; class Big { public: template<void (Small::*fn)()> void doit() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(fn)); } template<class T, void (Small::*fn)(T)> void doit(T x) { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::bind2nd(std::mem_fun(fn), x)); } public: std::vector<Small *> VectorOfSmalls; }; int main() { Big b; b.VectorOfSmalls.push_back(new Small); b.VectorOfSmalls.push_back(new Small); b.doit<&Small::foo>(); b.doit<int, &Small::bar>(5); }
458,549
458,567
How does one share data between a C++app and a C# app without files?
I have a C++ application with data that needs to be shared with a C# application. I'm currently transferring the data via files, but with speed and quantity of the data becoming an issue I would like to find a way to share the data through memory. I'm a beginner to intermediate programmer at best, and so far I have heard of two methods that may be able to help me do this: Socket Programming & Memory Mapped Files So my questions is, which is the best way to do this? (yes, speed is a factor) and any info or links to info that could help me in my research and comprehension of the method you suggest would be very much appreciated. Thank you,
You could use named pipes for interprocess communication. I haven't used it from c++ land yet though..
458,721
458,738
Disadvantages of a <std.h> file that brings in all std headers?
I find long sequences of standard includes annoying: #include <vector> #include <string> #include <sstream> #include <iostream> Considering these header files change only very rarely, is there a reason why I should not make a "std.h" file #including all std headers and just use that everywhere?
Including unnecessary header files will increase compile times.
458,795
458,893
Friend template functions (in non-template classes), C++
If I have a non-template (i.e. "normal") class and wish to have a template friend function, how do I write it without causing a compiler error? Here is an example to illustrate what I am trying to do: template <class T> void bar(T* ptr); class MyClass // note that this isn't a template class { private: void foo(); template <class T> friend void bar(T*); // ERROR: compiler gives me all kinds of grief }; template <class T> void bar(T* ptr) { if (ptr) { MyClass obj; obj.foo(); } } I'm using Visual Studio 2005, and the specific error I'm given is error C2063, stating that "bar" isn't a function. What needs to be done differently here?
Are you sure what you've posted gives the error? The following (using Visual Studio 2005) works fine for me: #include <iostream> template <class T> void bar(T* ptr); class MyClass // note that this isn't a template class { private: void foo(); template <class T> friend void bar(T*); // ERROR: compiler gives me all kinds of grief }; void MyClass::foo() { std::cout << "fooed!" << std::endl; } template <class T> void bar(T* ptr) { if (ptr) { MyClass obj; obj.foo(); } } int _tmain(int argc, _TCHAR* argv[]) { int someObj = 1; bar(&someObj); return 0; }
459,107
459,527
.NET marshalling speed
I have a C++ method signature that looks like this: static extern void ImageProcessing( [MarshalAs(UnmanagedType.LPArray)]ushort[] inImage, [MarshalAs(UnmanagedType.LPArray)]ushort[] outImage, int inYSize, int inXSize); I've wrapped the function in timing methods, both internal and external. Internally, the function is running at 0.24s. Externally, the function runs in 2.8s, or about 12 times slower. What's going on? Is marshalling slowing me down that much? If it is, how can I get around that? Should I go to unsafe code and use pointers or something? I'm sort of flummoxed as to where the extra time cost is coming from.
The answer is, sadly, far more mundane than these suggestions, although they do help. Basically, I messed up with how I was doing timing. The timing code that I was using was this: Ipp32s timer; ippGetCpuFreqMhz(&timer); Ipp64u globalStart = ippGetCpuClocks(); globalStart = ippGetCpuClocks() *2 - globalStart; //use this method to get rid of the overhead of getting clock ticks //do some stuff Ipp64u globalEnd = ippGetCpuClocks(); globalEnd = ippGetCpuClocks() *2 - globalEnd; std::cout << "total runtime: " << ((Ipp64f)globalEnd - (Ipp64f)globalStart)/((Ipp64f)timer *1000000.0f) << " seconds" << std::endl; This code is specific to the intel compiler, and is designed to give extremely precise time measurements. Unfortunately, that extreme precision means a cost of roughly 2.5 seconds per run. Removing the timing code removed that time constraint. There still appears to be a delay of the runtime, though-- the code would report 0.24 s with that timing code on, and is now reporting timing of roughly 0.35s, which means that there's about a 50% speed cost. Changing the code to this: static extern void ImageProcessing( IntPtr inImage, //[MarshalAs(UnmanagedType.LPArray)]ushort[] inImage, IntPtr outImage, //[MarshalAs(UnmanagedType.LPArray)]ushort[] outImage, int inYSize, int inXSize); and called like: unsafe { fixed (ushort* inImagePtr = theInputImage.DataArray){ fixed (ushort* outImagePtr = theResult){ ImageProcessing((IntPtr)inImagePtr,//theInputImage.DataArray, (IntPtr)outImagePtr,//theResult, ysize, xsize); } } } drops the executable time to 0.3 s (average of three runs). Still too slow for my tastes, but a 10x speed improvement is certainly within the realm of acceptability for my boss.
459,372
459,400
Putting a close button on QTabWidget
I'm using a QTabWidget to render multiple documents in a window, and I want to draw a close button on each tab. I'm using Vista and Qt4, so the tab widget is a native windows control; this may affect the feasibility. Does anyone know if it is possible to do this using the QTabWidget control, or do I have to create a custom widget? If creating a new widget is the only option, any pointers would be much appreciated; I'm relatively new to Qt.
Currently there is no way to do this with the stock QTabWidget, however the upcoming Qt 4.5 (planned to be released in March 2009) will have the ability to add close buttons to tabs either manually or by setting a QTabBar.TabsClosable property. Until then, the only way to get close buttons is to subclass QTabWidget or QTabBar and add it manually (possible, but not trivial).
459,386
459,413
C++ metaprogramming - generating errors in code
Is there a way that I can create a function that takes an int template parameter, and have that function give a compile time error if the value passed to the function is less than 10? The following code does not work, but it shows what I want to accomplish: template <int number1> void reportErrorIfLessThan10() { #if(number1 < 10) #error the number is less than 10 #endif } int maint(int argc, char**argv) { reportErrorIfLessThan10<5>();//report an error! reportErrorIfLessThan10<12>();//ok return 0; }
If you don't want Boost C++ Libraries magic and want bare bones... template<bool> class static_check { }; template<> class static_check<false> { private: static_check(); }; #define StaticAssert(test) static_check<(test) != 0>() Then use StaticAssert. It's a #define for me because I have code that needs to run in a lot of environments where C++ doesn't work right for templates and I need to just back it off to a runtime assert. :( Also, not the best error messages.
459,414
459,421
boost weak_ptr_cast in shared_from_this()
I'm using boost's shared pointers, and enable_shared_from_this to enable returning a shared pointer to this. Code looks like this: class foo : public boost::enable_shared_from_this<foo> { boost::shared_ptr<foo> get() { return shared_from_this(); } } Why would shared_from_this throw a weak_ptr_cast exception?
If you declared foo on the stack, so that there are no other shared pointers to foo. For example: void bar() { foo fooby; fooby.get(); } fooby.get() would throw the weak_ptr_cast exception. To get around this, declare fooby on the heap: void bar() { boost::shared_ptr<foo> pFooby = boost::shared_ptr<foo>(new foo()); pFooby->get(); } Another possibility is that you're trying to use shared_from_this before the constructor is done, which would again try to return a shared pointer that doesn't exist yet.
459,503
459,535
How can I avoid dynamic_cast in my C++ code?
Let's say I have the following class structure: class Car; class FooCar : public Car; class BarCar : public Car; class Engine; class FooEngine : public Engine; class BarEngine : public Engine; Let's also give a Car a handle to its Engine. A FooCar will be created with a FooEngine* and a BarCar will be created with a BarEngine*. Is there a way to arrange things so a FooCar object can call member functions of FooEngine without downcasting? Here's why the class structure is laid out the way it is right now: All Cars have an Engine. Further, a FooCar will only ever use a FooEngine. There are data and algorithms shared by all Engines that I'd rather not copy and paste. I might want to write a function that requires an Engine to know about its Car. As soon as I typed dynamic_cast when writing this code, I knew I was probably doing something wrong. Is there a better way to do this? UPDATE: Based on the answers given so far, I'm leaning towards two possibilities: Have Car provide a pure virtual getEngine() function. That would allow FooCar and BarCar to have implementations that return the correct kind of Engine. Absorb all of the Engine functionality into the Car inheritance tree. Engine was broken out for maintenance reasons (to keep the Engine stuff in a separate place). It's a trade-off between having more small classes (small in lines of code) versus having fewer large classes. Is there a strong community preference for one of these solutions? Is there a third option I haven't considered?
I'm assuming that Car holds an Engine pointer, and that's why you find yourself downcasting. Take the pointer out of your base class and replace it with a pure virtual get_engine() function. Then your FooCar and BarCar can hold pointers to the correct engine type. (Edit) Why this works: Since the virtual function Car::get_engine() would return a reference or a pointer, C++ will allow derived classes to implement this function with a different return type, as long as the return type only differs by being a more derived type. This is called covariant return types, and will allow each Car type to return the correct Engine.
459,649
459,727
Can I simplify this?
typedef void (FunctionSet::* Function)(); class MyFunctionSet : public FunctionSet { protected: void addFunctions() { addFunction(Function(&MyFunctionSet::function1)); } void function1() { // Do something. } }; The addFunction method adds the function to a list in the base class, which can then be enumerated to call all functions. Is there any way to simplify (less typing work) the adding of functions?
Looks like you assign a member function pointer to a function of the derived class to a member function pointer to a function of the base class. Well, that's forbidden, because it opens up a hole in the type-system. It comes at a surprise (at least for me, the first time i heard that). Read this answer for why. To answer your actual question - i would make addFunction a template: void addFunctions() { addFunction(&MyFunctionSet::function1); } Change addFunction in the base-class to this: template<typename Derived> void addFunction(void(Derived::*f)()) { myFunctions.push_back(static_cast<Function>(f)); } Better use static_cast, because it will tell you if Derived isn't actually derived from FunctionSet.
459,794
462,420
Why would SDL_Mixer not play music for certain mp3s?
Why would SDL_Mixer not play music for certain mp3s? I am utilizing SDL_Mixer for music playback in an application I am creating. On certain songs (entire albums actually), the music will simply not play without returning any errors. The music data loads successfully using Mix_LoadMUS and when executing Mix_PlayMusic with that data, it oddly enough returns 0 for success but plays no music. I have also tried reading Mix_GetError() and SDL_GetError() (I believe they're the same) to see if it raises an error, but no such luck. My question is, what other reasons would SDL_mixer not be able to play a particular mp3? I know the mp3's are functional since I can play them in other music players. I also know for a fact that they are not playing (as opposed to perhaps the volume being turned down) since Mix_PlayingMusic returns 0. Thanks everyone!
This actually wound up being a sound issue with that particular computer. Upon trying the same tests on another machine, the sound worked flawlessly. Just a quick note in case someone else encounters this issue.
459,901
459,914
window handlers for opengl
I've been programming opengl using glut as my window handler, lately i've been thinking if there are any advantages to switching to an alternate window handler such as wxWidgets or qt. Are there any major differences at all or is it just a matter of taste? Since glut provides some additional functions for opengl-programming beyond the window handling features, would there be a point in combining an additional toolkit with glut?
I can only speak from experiential of using QT: Once you have the basic structure set up then it is a simple case of doing what you have always done: for example, the project I am working on at the moment has an open gl widget embedded in the window. This widget has functions such as initializeGL, resize...paintGL etc. Advantages include the ability to pass variables to an from the other windows / widgets etc. QT also has additional functions for handelling mouse clicks and stuff (great for 2d stuff, 32d stuff requires some more complex maths)
459,942
459,970
Defining class string constants in C++?
I have seen code around with these two styles , I am not not sure if one is better than another (is it just a matter of style)? Do you have any recommendations of why you would choose one over another. //Example1 class Test { private: static const char* const str; }; const char* const Test::str = "mystr"; //Example2 class Test { private: static const std::string str; }; const std::string Test::str ="mystr";
Usually you should prefer std::string over plain char pointers. Here, however, the char pointer initialized with the string literal has a significant benefit. There are two initializations for static data. The one is called static initialization, and the other is called dynamic initialization. For those objects that are initialized with constant expressions and that are PODs (like pointers), C++ requires that their initialization happens at the very start, before dynamic initialization happens. Initializing such an std::string will be done dynamically. If you have an object of a class being a static object in some file, and that one needs to access the string during its initialization, you can rely on it being set-up already when you use the const char* const version, while using the std::string version, which isn't initialized statically, you don't know whether the string is already initialized - because the order of initialization of objects across translation unit boundaries is not defined.
460,281
460,298
C++ Forward Declaration Problem when calling Method
I have a problem which I think is related to forward declarations, but perhaps not. Here is the relevant code: A.h #ifndef A_H_ #define A_H_ #include "B.h" class A { private: B b; public: A() : b(*this) {} void bar() {} }; #endif /*A_H_*/ B.h #ifndef B_H_ #define B_H_ #include "A.h" class A; class B { private: A& a; public: B(A& a) : a(a) {} void foo() { /*a.bar();*/ } //doesn't compile }; #endif /*B_H_*/ main.cpp #include "A.h" int main() { A a; return 0; } The problem seems to be with the invocation of A::bar(). The program successfully compiles until I attempt to call this method at which point I get two errors: error: invalid use of incomplete type ‘struct A’ error: forward declaration of ‘struct A’ I presume this is because A::bar() has yet to be defined or declared since both headers reference each other. However, I forward declared class A and am at a loss as to what else I need to do. I am new to C++, so please forgive me. I could not find the answer to this question anywhere else online. As always, thanks in advance!
You've got a circular reference, so you need to separate B.h. Try something like: B.h: #ifndef B_H_ #define B_H_ // don't include A.h here! class A; class B { private: A& a; public: B(A& a) : a(a) {} void foo(); }; #endif /*B_H_*/ B.cpp: #include "B.h" #include "A.h" void B::foo() { a.bar(); } // now you're ok Edit: explanation for why you need to split it into two files: The class B contains a reference to A, which can be a so-called incomplete type. You can't call any functions on it because the compiler doesn't yet know what the heck A is - it just knows that it's a class of some sort. Once you include A.h (in the .cpp file), then A is a complete type, and you can do whatever you like with it. You can't keep the whole thing in one header file because you'll get a circular reference. You're preventing an infinite loop with your include guards, but you're getting something you don't want. Look at what the compiler ends up with when you compile main.cpp, as you had it before: // #include "A.h" ==> #define A_H_ // #include "B.h" ==> #define B_H_ // #include "A.h" ==> nothing happens! (since A_H_ is already defined) class A; class B { private: A& a; public: B(A& a) : a(a) {} void foo() { a.bar(); } // <-- what the heck is A here? // it's not defined until below }; class A { private: B b; public: A() : b(*this) {} void bar() {} }; int main() { A a; return 0; }
460,426
460,433
I want to start Qt development - what basic knowledge in C++ and OS do I have to own?
I'm going to learn Qt and I just want to know what parts of C++, OO design and other things I must have background in? Templates, RAII, Patterns, ....?
QT is no different from any other platform or library you can use. To use it properly you only need to know the basics of C++ and how to compile and build your code. This tutorial takes you through the basics of building a QT application. Of course like any other programming endeavor, the more you know about the language and tools you're using, the better.
460,583
461,292
How can I shift elements inside STL container
I want to shift elements inside container on any positions to the left or right. The shifting elements are not contiguous. e.g I have a vector {1,2,3,4,5,6,7,8} and I want to shift {4,5,7} to the left on 2 positions, the expected result will be {1,4,5,2,7,3,6,8} Is there an elegant way to solve it ?
You can write your own shifting function. Here's a simple one: #include <iterator> #include <algorithm> template <typename Container, typename ValueType, typename Distance> void shift(Container &c, const ValueType &value, Distance shifting) { typedef typename Container::iterator Iter; // Here I assumed that you shift elements denoted by their values; // if you have their indexes, you can use advance Iter it = find(c.begin(), c.end(), value); Iter tmp = it; advance(it, shifting); c.erase(tmp); c.insert(it, 1, value); } You can then use it like that: vector<int> v; // fill vector to, say, {1,2,3,4,5} shift(v, 4, -2); // v = {1,4,2,3,5} shift(v, 3, 1); // v = {1,4,2,5,3} This is a naive implementation, because when shifting multiple elements, find will iterate many times on the beginning of the container. Moreover, it assumes that every element is unique, which might not be the case. However, I hope it gave you some hints on how to implement what you need.
460,613
460,703
#ifdef in switch statement bug?
I have some code that looks like this: someFunc(value) { switch(value){ case 1: case 2: case 3: #ifdef SOMEMACRO case 4: case 5: #endif return TRUE; } return FALSE; } SOMEMACRO is defined, and let's say the value is 4.. Why does case 4 and 5 get skipped and FALSE is returned instead? :( Is it because I don't have a default case or am I not allowed to use an ifdef in the switch statement?
"switch" Isn't Broken to, more or less, quote The Pragmatic Programmer. Go ahead and look somewhere else for the error. To convince yourself add value = 4 and #define SOMEMACRO right there in someFunc. Make a clean build to make sure every dependancy is resolved.
460,666
460,790
decreasing cache misses through good design
How to decrease the number of possible cache misses when designing a C++ program? Does inlining functions help every time? or is it good only when the program is CPU-bounded (i.e. the program is computation oriented not I/O oriented)?
Here are some things that I like consider when working on this kind of code. Consider whether you want "structures of arrays" or "arrays of structures". Which you want to use will depend on each part of the data. Try to keep structures to multiples of 32 bytes so they pack cache lines evenly. Partition your data in hot and cold elements. If you have an array of objects of class o, and you use o.x, o.y, o.z together frequently but only occasionally need to access o.i, o.j, o.k then consider puting o.x, o.y, and o.z together and moving the i, j, and k parts to a parallel axillary data structure. If you have multi dimensional arrays of data then with the usual row-order layouts, access will be very fast when scanning along the preferred dimension and very slow along the others. Mapping it along a space-filling curve instead will help to balance access speeds when traversing in any dimension. (Blocking techniques are similar -- they're just Z-order with a larger radix.) If you must incur a cache miss, then try to do as much as possible with that data in order to amortize the cost. Are you doing anything multi-threaded? Watch out for slowdowns from cache consistency protocols. Pad flags and small counters so that they'll be on separate cache lines. SSE on Intel provides some prefetch intrinsics if you know what you'll be accessing far enough ahead of time.
460,809
461,174
C++: Dll unloading issue
How can I ensure a dll is not unloaded while any objects in it exist? The problem is, when I was using explict memory management I could delete the dll objects before freeing the dll, however with smart pointers I have no controll over the order there destroyed, meaning the dll may be freed first causeing a crash when trying to free one of the other objects: FlPtr is a simple refrence counting class thats calls AddRef and Release as needed ExampleDll *dll = LoadDll(L"bin\\example.dll"); IObject *obj = dll->CreateObject(); ... obj->Release(); delete dll;//fine because all objects already deleted return 0; auto_ptr<ExampleDll> dll = LoadDll(L"bin\\example.dll"); FlPtr<IObject> obj = dll->CreateObject(); ... return 0;//crash if dll is destructed before obj since Object::Release needs to call into the dll I tried making the dll handle unloading itsself, ie only unload after all objects have been deleted. This work by creating a new object IExampleDll which the dll implements. This is like the ExampleDll object from before but lives in the dll rather than the exe and is also refrence counted. Each object in the dll increments this refrence on contruction and deincrements it on destruction. This means the refrence count only reaches zero when the exe has Released its refrences AND all the dlls objects have been destroyed. It then deletes itsself calling FreeLibrary(GetModuleHandle()) in its destructor. This however crashes at the FreeLibrary, im asuming because the thread is still in the dlls code that is being unloaded... I'm at a loss now how to make sure the dll is only unloaded when there are no remaining objects, apart from going back to freeing the dll explicitly after everything else should have been deleted; int main() { ExampleDll *dll = LoadDll("bin\\example.dll"); restOfProgram(); delete dll; } This approach becomes difficult when dlls need to be loaded/unloaded mid program saftly, ie if the user changed from d3d to openGL in options.
Assuming you do not want to terminate the thread when unloading the library (otherwise, see MSalters), you need to free the library from the caller that loaded it. COM solves that by an in-DLL instance counter (much like yours, if I understand you correctly), and regulary checking it by calling a global exported CanUnloadNow function. Another option is to have your object/interface smart pointers ALSO reference the DLL they came from. This would increase the client data size, but you wouldn't need to touch the DLL. You might even recycle the LoadLibrary/FreeLibrary reference counter, however that might hit performance. Also, none of these schemes help much if you get circular DLL dependencies (Component DllA.X references DllB.Y, which references DllA.Z). I haven't yet fould a good solution to that that doesn#t requrie global knowledge.
460,847
460,897
Using std::for_each on polymorphic method in c++
When using the std::for_each, class A; vector<A*> VectorOfAPointers; std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo)); If we have classes inheriting from A and implementing foo(), and we hold a vector of pointers to A, is there any way to call a polymorphic call on foo(), rather then explicitly calling A::foo()? Note: I can't use boost, only standard STL. Thanks, Gal
It actually works this way. #include <algorithm> #include <iostream> #include <functional> #include <vector> struct A { virtual void foo() { std::cout << "A::foo()" << std::endl; } }; struct B: public A { virtual void foo() { std::cout << "B::foo()" << std::endl; } }; int main() { std::vector<A*> VectorOfAPointers; VectorOfAPointers.push_back(new B()); std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo)); return 0; } prints B::foo() So it does exactly what you want. Check that virtual keywords are present though, it's easy to forget them.
460,869
460,889
for_each on a COM IEnumXxx interface?
I've got a COM object that returns an IEnumUnknown. Is there anything out there that'll turn it into an STL-style iterator? So that I can do something like this: IEnumUnkPtr pEnumUnk; // ...something that fills in pEnumUnk... MagicThing m(pEnumUnk); std::for_each(m.begin(), m.end(), DoSomethingWithUnk); ...or similar?
Seems like the comstl project has what you need: http://www.stlsoft.org/doc-1.9/classcomstl_1_1enumerator__sequence.html
460,980
460,996
Where can I find the default icons used for folders and applications?
I'm trying to load the default HICON that explorer displays for: An open folder An exe that has no embedded default icon of its own. This can also be seen in 'Add/Remove Programs' or 'Programs and Features' as it's called on Vista. Do you know where these can be found? I think the folder icon might be in the resources of explorer.exe. But have no idea where the default application icon can be retrieved from. And additionally, do you have any sample code that could load them into HICONs. I really need this to work on multiple Windows OSs: 2000, XP, Vista, 2008 Thanks for the help so far. I'm on Vista and have looked through Shell32.dll. I don't see an icon in there that looks the same as the default one displayed by an application in explorer. I could be missing it - there are 278 icons to look through - is it definitely in there, or is there some other location I should look?
I think they are in %windir%\system32\SHELL32.dll Found some code in the internet, try if that works: HINSTANCE hDll; hDll = LoadLibrary ( "SHELL32.dll" ); wincl.hIcon = LoadIcon (hDll , MAKEINTRESOURCE ( 1 )); wincl.hIconSm = LoadIcon (hDll, MAKEINTRESOURCE ( 2 )); Edit: Windows has a lot more icons in the "moricons.dll", but I think the file and folder icons should all be in the shell32.dll. Remind, that icons in Vista have different resolutions, up to 256x256, so the icon you are looking at a resolution 32x32 might look different then the full resolution version of the same icon.
461,062
461,190
C++ anonymous variables
Why won't this work? 0. #define CONCAT(x, y) x ## y 1. 2. #define VAR_LINE(x) \ 3. int CONCAT(_anonymous, __LINE__) = x 4. 5. #define VAR_LINE2(x) \ 6. int _anonymous ## x = 1 7. 8. int main() 9. { 10. VAR_LINE(1); 11. VAR_LINE(1); 12. VAR_LINE(1); 13. VAR_LINE2(__LINE__); 14. } The result from the above macro expansion int _anonymous__LINE__ = 1; int _anonymous__LINE__ = 1; int _anonymous__LINE__ = 1; int _anonymous13 = 1; It would be convenient if I didn't have to write that __LINE__ macro as an argument. I'm thinking the problem is pretty clear. I want to be able to generate anonymous variables so that this macro doesn't fail with redefinition error when declaring several variables within the same scope. My idea was to use the predefined __LINE__ macro because no variable will ever be declared on the same line like this. But the macro expansion troubles me, can you help? Update: Correct answer Thanks to Luc Touraille. However, there was a tiny problem with the suggested solution. There has to be whitespace between the operands and the ## operator (apparently the standard says otherwise but the the PS3 flavoured GCC would not expand the macro properly if there were no whitespace between the operator and operands). #define _CONCAT(x,y) x ## y #define CONCAT(x,y) _CONCAT(x,y) The VAR_LINE macro now yields: int _anonymous10 = 1; int _anonymous11 = 1; int _anonymous12 = 1; This has been verified to work under Win32 (Visual Studio 2008), XBOX360 (Xenon) and PS3.
You need to add a level of indirection so that __LINE__ will be expanded: #define _CONCAT_(x,y) x ## y #define CONCAT(x,y) _CONCAT_(x,y) #define VAR_LINE(x) int CONCAT(_anonymous, __LINE__) = x
461,093
461,107
Viewing compiler expanded code - C++
I learned that compiler will expand macros while compiling. Templates are also expanded at the compile time. Is there any way to see this expanded code? I am compiling using Visual Studio 2008. any thoughts?
The VC++ compiler (cl.exe) supports a few command line switches for this: /E preprocess to stdout /P preprocess to file /EP preproscess to stdout with no #lines Additional command-line switches can be added in your project properties. In my version (VC2005), Configuration Options -> C/C++ -> Command Line -> Additional Options
461,203
461,224
When to use virtual destructors?
I have a solid understanding of most OOP theory but the one thing that confuses me a lot is virtual destructors. I thought that the destructor always gets called no matter what and for every object in the chain. When are you meant to make them virtual and why?
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class: class Base { // some virtual methods }; class Derived : public Base { ~Derived() { // Do some important cleanup } }; Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet: Base *b = new Derived(); // use b delete b; // Here's the problem! Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour: [In delete b], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak. To sum up, always make base classes' destructors virtual when they're meant to be manipulated polymorphically. If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete on a base class pointer. You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.
461,236
461,250
How to cast a pointer in C++
void foo(void **Pointer); int main () { int *IntPtr; foo(&((void*)IntPtr)); } Why do I get an error? error: lvalue required as unary ‘&’ operand Thanks
(void*) is not an lvalue, it is kind of a casting operator, you need to have the ampersand to the immediate left of the variable (lvalue). This should be right: foo(((void**)&IntPtr));
461,449
461,528
return statement vs exit() in main()
Should I use exit() or just return statements in main()? Personally I favor the return statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having return seems like a better choice than exit(). Does exit() do anything special that return doesn't?
Actually, there is a difference, but it's subtle. It has more implications for C++, but the differences are important. When I call return in main(), destructors will be called for my locally scoped objects. If I call exit(), no destructor will be called for my locally scoped objects! Re-read that. exit() does not return. That means that once I call it, there are "no backsies." Any objects that you've created in that function will not be destroyed. Often this has no implications, but sometimes it does, like closing files (surely you want all your data flushed to disk?). Note that static objects will be cleaned up even if you call exit(). Finally note, that if you use abort(), no objects will be destroyed. That is, no global objects, no static objects and no local objects will have their destructors called. Proceed with caution when favoring exit over return. http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a
461,507
479,471
How to use BOOST_FOREACH with a boost::ptr_map?
How can I use BOOST_FOREACH efficiently (number-of-character/readability-wise) with a boost::ptr_map? Kristo demonstrated in his answer that it is possible to use BOOST_FOREACH with a ptr_map, but it does not really save me any typing (or makes my code really more readable) than iterating over the ptr_map with an iterator: typedef boost::ptr_container_detail::ref_pair<int, int* const> IntPair; BOOST_FOREACH(IntPair p, mymap) { int i = p.first; } // vs. boost::ptr_map<int, T>::iterator it; for (it = mymap.begin(); it != mymap.end(); ++it) { // doSomething() } The following code is somewhere along the lines what I wish for. It follows the standard way on how to use BOOST_FOREACH with a std::map. Unfortunately this does not compile: boost::ptr_map<int, T> mymap; // insert something into mymap // ... typedef pair<int, T> IntTpair; BOOST_FOREACH (IntTpair &p, mymap) { int i = p.first; }
As STL style containers, the pointer containers have a value_type typedef that you can use: #include <boost/ptr_container/ptr_map.hpp> #include <boost/foreach.hpp> int main() { typedef boost::ptr_map<int, int> int_map; int_map mymap; BOOST_FOREACH(int_map::value_type p, mymap) { } } I find that using a typedef for the container makes the code a lot easier to write. Also, you should try to avoid using the contents of detail namespaces in boost, it's a boost convention that they contain implementation details.
461,535
461,548
Using an asterisk in a RegExp to extract data that is enclosed by a certain pattern
I have an text that consists of information enclosed by a certain pattern. The only thing I know is the pattern: "${template.start}" and ${template.end} To keep it simple I will substitute ${template.start} and ${template.end} with "a" in the example. So one entry in the text would be: aINFORMATIONHEREa I do not know how many of these entries are concatenated in the text. So the following is correct too: aFOOOOOOaaASDADaaASDSDADa I want to write a regular expression to extract the information enclosed by the "a"s. My first attempt was to do: a(.*)a which works as long as there is only one entry in the text. As soon as there are more than one entries it failes, because of the .* matching everything. So using a(.*)a on aFOOOOOOaaASDADaaASDSDADa results in only one capturing group containing everything between the first and the last character of the text which are "a": FOOOOOOaaASDADaaASDSDAD What I want to get is something like captureGroup(0): aFOOOOOOaaASDADaaASDSDADa captureGroup(1): FOOOOOO captureGroup(2): ASDAD captureGroup(3): ASDSDAD It would be great to being able to extract each entry out of the text and from each entry the information that is enclosed between the "a"s. By the way I am using the QRegExp class of Qt4. Any hints? Thanks! Markus Multiple variation of this question have been seen before. Various related discussions: Regex to replace all \n in a String, but no those inside [code] [/code] tag Using regular expressions how do I find a pattern surrounded by two other patterns without including the surrounding strings? Use RegExp to match a parenthetical number then increment it Regex for splitting a string using space when not surrounded by single or double quotes What regex will match text excluding what lies within HTML tags? and probably others...
Simply use non-greedy expressions, namely: a(.*?)a
461,580
462,366
Persistence solutions for C++ (with a SQL database)?
I'm wondering what kind of persistence solutions are there for C++ with a SQL database? In addition to doing things with custom SQL (and encapsulating the data access to DAOs or something similar), are there some other (more general) solutions? Like some general libraries or frameworks (something like Hibernate & co for Java and .NET) or something else? (Something that I haven't even thought of can also be welcome to be suggested) EDIT: Yep, I was searching more for an ORM solution or something similar to handle sql queries and the relationships between tables and objects than for the db engine itself. Thanks for all the answers anyway!
It sounds like you are looking for some ORM so that you don't have to bother with hand written SQL code. There is a post here that goes over ORM solutions for C++. You also did not mention the type of application you are writing, if it is a desktop application, mobile application, server application. Mobile: You are best off using SQLite as your database engine because it can be embedded and has a small footprint. Desktop App: You should still consider using SQLite here, but you also have the option with most desktop applications to have an always on connection to the internet in which case you may want to provide a network server for this task. I suggest using Apache + MySQL + PHP and using a lightweight ORM such as Outlet ORM, and then using standard HTTP post calls to access your resources. Server App: You have many more options here but I still suggest using Apache + MySQL + PHP + ORM because I find it is much easier to maintain this layer in a script language than in C++.
461,711
6,170,155
Dealing with "C compiler cannot create executables" in Cygwin
Whatever I try to compile in Cygwin I get the following output: checking for mingw32 environment... no checking for EMX OS/2 environment... no checking how to run the C preprocessor... gcc -E checking for gcc... gcc checking whether the C compiler (gcc ) works... no configure: error: installation or configuration problem: C compiler cannot creat e executables. The last few lines of the logfile look like this: configure:2810: checking for EMX OS/2 environment configure:2822: gcc -c conftest.c 1>&5 configure: In function `main': configure:2818: error: `__EMX__' undeclared (first use in this function) configure:2818: error: (Each undeclared identifier is reported only once configure:2818: error: for each function it appears in.) configure: failed program was: #line 2815 "configure" #include "confdefs.h" int main() { return __EMX__; ; return 0; } configure:2838: checking how to run the C preprocessor configure:2859: gcc -E conftest.c >/dev/null 2>conftest.out configure:2943: checking for gcc configure:3056: checking whether the C compiler (gcc ) works configure:3072: gcc -o conftest conftest.c -llib 1>&5 /usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/bin/ld: cannot find -llib collect2: ld returned 1 exit status configure: failed program was: #line 3067 "configure" #include "confdefs.h" main(){return(0);} This is a fresh Cygwin install with G++ and a bunch of other devtools added. Any idea what I need to do to get this thing working? Update 0: Nick, your link to http://www.geektimes.com/linux/troubleshooting/c-cant-create-executables.html was tried already - unfortunately this instructions are for redhat and do not seem to apply to cygwin.
Your Configure is wrong. Usually autoreconf -f helps. If not you need to check the failing rule and fix it.
461,773
464,917
What is the easiest way to convert a compressed wav file to an uncompressed wav file in C# or C++?
What is the easiest way to programatically convert a compressed wav file (MPEG codec for example, but could be any installed codec) to an uncompressed wav file (16 bit PCM)? I've heard that using direct show and writing the code in native C++ would do it, but I've not had much experience with direct show. Is there an easier way to do this? C# that would be ideal, but C++ would also be fine too.
You can decompress WAV files in C# using any ACM codec installed on your PC using NAudio. Here's some sample code: using (WaveFileReader reader = new WaveFileReader(inputFileName)) { using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader)) { WaveFileWriter.CreateWaveFile(outputFileName, convertedStream); } }
461,836
727,836
Arduino C++ code: can you use virtual functions and exceptions?
Following up on this comment from the question Writing firmware: assembly or high level?: When compiling C++ code for the Arduino platform, can you use virtual functions, exceptions, etc? Or would you want to (have to) use a subset of C++ (as described in the comment)? Any other caveats when programming for the Arduino platform?
The Arduino environment uses the AVR version of the GCC toolchain. The code is compiled as C++, so you can use classes. Virtual functions are possible; the vtables will be stored in the .data section and have the correct addresses. In fact, the Print base class uses virtual functions to adapt the various "print" methods to the different output types. Exceptions are not supported because of code space reasons. The Arduino environment passes "-fno-exceptions" to the compiler command line. See the source for verification of this. Templates are supported. For example, this no-cost stream insertion operator technique works fine using a simple template and inline operator.
461,870
462,001
Selecting an index in a QListView
This might be a stupid question, but I can't for the life of me figure out how to select the row of a given index in a QListView. QAbstractItemView , QListView's parent has a setCurrentIndex(const QModelIndex &index). The problem is, I can't construct a QModelIndex with the row number I want since the row and column field of the QModelIndex has no mutators. QTableView, which also inherits from QAbstractItemView has a selectRow(int row) function, why in the seven hells doesn't the QListView have this? Good ol' windows forms has the SelectedIndex property on it's listviews.
You construct the QModelIndex by using the createIndex(int row, int column) function of the model you gave to the view. QModelIndexes should only be used once, and must be created by the factory in the model.
461,918
462,242
Is that a good idea to define exception with template?
I am thinking is that a good idea to define exception with template. Defining different types of exception is a super verbose task. You have to inherit exception, there is nothing changed, just inherit. Like this.. class FooException : public BaseException { public: ... }; class BarException : public BaseException { public: ... }; ... That's a nightmare isn't it? So I am considering to define different exception with template /** @brief Exception of radio **/ class Exception : public runtime_error { private: /// Name of file that throw const string m_FileName; /// Line number of file that throw size_t m_Line; public: Exception(const string &what, const string &File, size_t Line) throw() : runtime_error(what), m_FileName(File), m_Line(Line) {} virtual ~Exception() throw() {} /** @brief Get name of file that throw @return Name of file that throw **/ virtual const string getFileName() const throw() { return m_FileName; } /** @brief Get throw exception line @return Throw exception line **/ virtual size_t getLine() const throw() { return m_Line; } /** @brief Get description of this exception @return Description of this exception **/ virtual const string getMessage() const throw() { return what(); } virtual void print(ostream &stream = cerr) const throw() { stream << "# RunTimeError #" << endl; stream << "Error : " << what() << endl; stream << "File : " << getFileName() << endl; stream << "Line : " << getLine() << endl; } }; /** @brief Template exception of radio **/ template <typename T> class TemplateException : public Exception { public: TemplateException (const string &what, const string &File, size_t Line) throw() : Exception(what, File, Line) {} virtual ~TemplateException () throw() {} }; } #define THROW(type, error) (throw TemplateRadioException<type>( (error), __FILE__, __LINE__)) So if I have to define a new exception, I can just define a empty class like this. class NuclearException {}; To throw exception THROW(NuclearException , "Boom!!"); To catch try { } catch (TemplateException<NuclearException> &e) { // ... } If we want to catch all exception, we can write this try { } catch (Exception &e) { // ... } It works fine, but I don't sure are there any side effects? Is this a good idea to define different type of exception? Or there is better solution? I have no idea :S Thanks. Victor Lin.
It's definitely possible and works fine, but i would avoid it. It obscures diagnostics. GCC will display the name of the exception type, with the usual template stuff included. I would take the few minutes to define the new exception class, personally. It's not like you would do it all the time.
461,981
462,046
Destructor vs member function race
When I'm inside a destructor is it possible that some other thread will start executing object's member function? How to deal with this situation?
C++ has no intrinsic protection against using an object after it's been deleting - forget about race conditions - another thread could use your object after it's been completely deleted. Either: Make sure only one place in the code owns the object, and it's responsible for deleting when no-one is using the object. Make the object reference counted - by added explicit reference counting code, or finding an appropriate base-class that implements reference counting
462,160
462,441
Launching a C++ executable from a C# app and keeping role based security context
First off I know this is probably a tall order but... :) We have some software that interacts with the hardware our company produces. This software loads a .NET assembly and this acts as our interface to the hardware. Currently we have a 'Launcher' application written in C# which provides role based security. This 'Launcher' launches the C++ executable with command line arguments (the .NET assembly to use) via a process. The C++ executable then loads the supplied .NET assembly and uses it to perform its actions. The problem is because I launch the C++ application in a process I lose the role based security context provided by the 'Launcher'. Is there any way I can launch the C++ application and keep the role based security context? Thanks for taking the time to read this. If you have any questions please let me know. Thank you, Adam
You would have to modify the C++ application to check the roles as well. If you can do that, you might consider breaking up part of your C# application into multiple assemblies. Specifically, take the roles part the C# application, and compile that as a dll with COM/ActiveX extensions. Then you can call the C# dll (via COM) to check permissions.
462,165
462,203
error: ‘NULL’ was not declared in this scope
I get this message when compiling C++ on gcc 4.3 error: ‘NULL’ was not declared in this scope It appears and disappears and I don't know why. Why? Thanks.
NULL is not a keyword. It's an identifier defined in some standard headers. You can include #include <cstddef> To have it in scope, including some other basics, like std::size_t.
462,180
462,739
Why doesn't C++ have a pointer to member function type?
I could be totally wrong here, but as I understand it, C++ doesn't really have a native "pointer to member function" type. I know you can do tricks with Boost and mem_fun etc. But why did the designers of C++ decide not to have a 64-bit pointer containing a pointer to the function and a pointer to the object, for example? What I mean specifically is a pointer to a member function of a particular object of unknown type. I.E. something you can use for a callback. This would be a type which contains two values. The first value being a pointer to the function, and the second value being a pointer to the specific instance of the object. What I do not mean is a pointer to a general member function of a class. E.G. int (Fred::*)(char,float) It would have been so useful and made my life easier. Hugo
@RocketMagnet - This is in response to your other question, the one which was labeled a duplicate. I'm answering that question, not this one. In general, C++ pointer to member functions can't portably be cast across the class hierarchy. That said you can often get away with it. For instance: #include <iostream> using std::cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout << "a.x == " << x << "\n";}}; int main() { typedef void (A::*pmf_t)(); C c; c.x = 42; c.y = -1; pmf_t mf = static_cast<pmf_t>(&C::foo); (c.*mf)(); } Compile this code, and the compiler rightly complains: $ cl /EHsc /Zi /nologo pmf.cpp pmf.cpp pmf.cpp(15) : warning C4407: cast between different pointer to member representations, compiler may generate incorrect code $ So to answer "why doesn't C++ have a pointer-to-member-function-on-void-class?" is that this imaginary base-class-of-everything has no members, so there's no value you could safely assign to it! "void (C::)()" and "void (void::)()" are mutually incompatible types. Now, I bet you're thinking "wait, i've cast member-function-pointers just fine before!" Yes, you may have, using reinterpret_cast and single inheritance. This is in the same category of other reinterpret casts: #include <iostream> using std::cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout << "a.x == " << x << "\n";}}; class D { public: int z; }; int main() { C c; c.x = 42; c.y = -1; // this will print -1 D& d = reinterpret_cast<D&>(c); cout << "d.z == " << d.z << "\n"; } So if void (void::*)() did exist, but there is nothing you could safely/portably assign to it. Traditionally, you use functions of signature void (*)(void*) anywhere you'd thing of using void (void::*)(), because while member-function-pointers don't cast well up and down the inheritance heirarchy, void pointers do cast well. Instead: #include <iostream> using std::cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout << "a.x == " << x << "\n";}}; void do_foo(void* ptrToC){ C* c = static_cast<C*>(ptrToC); c->foo(); } int main() { typedef void (*pf_t)(void*); C c; c.x = 42; c.y = -1; pf_t f = do_foo; f(&c); } So to your question. Why doesn't C++ support this sort of casting. Pointer-to-member-function types already have to deal with virtual vs non-virtual base classes, and virtual vs non-virtual member functions, all in the same type, inflating them to 4*sizeof(void*) on some platforms. I think because it would further complicate the implementation of pointer-to-member-function, and raw function pointers already solve this problem so well. Like others have commented, C++ gives library writers enough tools to get this done, and then 'normal' programmers like you and me should use those libraries instead of sweating these details. EDIT: marked community wiki. Please only edit to include relevant references to the C++ standard, and add in italic. (esp. add references to standard where my understanding was wrong! ^_^ )
462,252
462,271
Using static vs. member find method on a STL set?
I am using a set because, i want to use the quick look up property of a sorted container such as a set. I am wondering if I have to use the find member method to get the benefit of a sorted container, or can I also use the static find method in the STL algorithms? My hunch is that using the static version will use a linear search instead of a binary search like I want.
You are right that the non-member version does a linear search, while the member version will do a O(log N) search. std::set is optimized for O(log N) insertion, retrieval and deletion. As a point of definition, the std::find method is not a static function. See here for a description of the various things static can mean in C++.
462,860
472,175
C++ Library for image recognition: images containing words to string
Does anyone know of a c++ library for taking an image and performing image recognition on it such that it can find letters based on a given font and/or font height? Even one that doesn't let you select a font would be nice (eg: readLetters(Image image).
I've been looking into this a lot lately. Your best is simply Tesseract. If you need layout analysis on top of the OCR than go with Ocropus (which in turn uses Tesseract to do the OCR). Layout analysis refers to being able to detect position of text on the image and do things like line segmentation, block segmentation, etc. I've found some really good tips through experimentation with Tesseract that are worth sharing. Basically I had to do a lot of preprocessing for the image. Upsize/Downsize your input image to 300 dpi. Remove color from the image. Grey scale is good. I actually used a dither threshold and made my input black and white. Cut out unnecessary junk from your image. For all three above I used netbpm (a set of image manipulation tools for unix) to get to point where I was getting pretty much 100 percent accuracy for what I needed. If you have a highly customized font and go with tesseract alone you have to "Train" the system -- basically you have to feed a bunch of training data. This is well documented on the tesseract-ocr site. You essentially create a new "language" for your font and pass it in with the -l parameter. The other training mechanism I found was with Ocropus using nueral net (bpnet) training. It requires a lot of input data to build a good statistical model. In terms of invoking Tesseract/Ocropus are both C++. It won't be as simple as ReadLines(Image) but there is an API you can check out. You can also invoke via command line.
462,924
463,399
There is really something like Objective C++?
I'm reading a post about iPhone programming and I've noticed that the talk about Objective C++, the code shown in the post looks mainly like Objective-C but there also are several snippets in C++. Is it really possible to program Cocoa from C++?
In addition to the other comments, I would add that Objective-C++ is not exactly the same as "program Cocoa from C++" because there is no C++ to Cocoa bridge involved. In Objective-C++, you program the Cocoa API entirely with Objective-C objects/syntax. The Cocoa API remains unchanged, so you need to communicate with it in the same way (using Objective-C strings, Objective-C arrays and Objective-C objects). The difference with Objective-C++, compared to plain Objective-C, is that you can also use C++ objects (containing Objective-C objects, contained by Objective-C objects or just along-side Objective-C objects).
462,982
473,107
Putting a CGImageRef on the clipboard
I'm trying to copy a CGImageRef to the clipboard pasteboard. I found a function that claims it should do this by creating a destination from (zero sized), adding the image to the destination, finalizing, then PasteboardPutItemFlavor the ref into the clipboard. However it doesn't work, so two questions: Is this the correct way to go about this? (ie, is there just a small bug, or am I doing it wrong?) What type should I make the destination? The source had it as TIFF, but word doesn't seem to know how to deal with that, I changed it to PICT, which at least gave me the "paste" option, but then said it was too big... Code: void copyCGImageRefToPasteboard(CGImageRef ref) { OSStatus err = noErr; PasteboardRef theClipboard; err = PasteboardCreate( kPasteboardClipboard, &theClipboard ); err = PasteboardClear( theClipboard );// 1 CFMutableDataRef url = CFDataCreateMutable(kCFAllocatorDefault, 0); CFStringRef type = kUTTypePICT; size_t count = 1; CFDictionaryRef options = NULL; CGImageDestinationRef dest = CGImageDestinationCreateWithData(url, type, count, options); CGImageDestinationAddImage(dest, ref, NULL); CGImageDestinationFinalize(dest); err = PasteboardPutItemFlavor( theClipboard, (PasteboardItemID)1, type, url, 0 ); }
Ok, I'm answering my own question here, but here's what I've found: Apple wants you to use PDF for pasteboards. So if you swap out Pict with PDF, it pretty muc just works. However, MS Word (what I was testing with) only started to allow pasting of PDF in the newest version (Which I don't have). So, that's the solution, use PDF, and require Word 2008.
463,020
463,127
How can I get and set the 'read-only' property of an edit box?
How can I get and set the 'read-only' property of an edit box?
The CEdit class has a SetReadOnly method which can be called at run-time. Details on MSDN: http://msdn.microsoft.com/en-gb/library/aa279328(VS.60).aspx
463,240
463,269
What is the best way to pass information from java to c++?
I have a java application I need to pass some info to a C++ program. It has been suggested that I use some simple socket programming to do this. Is this the best way? If not what are the alternatives? If so, how should I go about learning about socket programming?
You have a few options: Pass a file from Java to C++. This is probably simplest. It's easy to test and shouldn't require any 3rd party libraries on either end. Use sockets as mentioned. In C++, if you require a cross-platform solution a library such as ACE or boost will save you some heartache Use JNI to call from Java to C++ or vice versa. This is probably the most difficult, but most performant. For learning sockets, a Google search for "java socket tutorial" or "c++ socket tutorial" will give you lots of information.
463,708
464,014
Wireless debugging of windows mobile applications
I'm trying to debug a windows mobile aplication using a wifi connection, on a Vista with Visual Studio 2008 following this instruction http://blogs.msdn.com/vsdteam/archive/2005/04/28/413304.aspx. It worked flawlessly with XP SP2, but not with Vista. Do you know if this is possible at all? or is another flaw from Vista?
It should work fine. I debug to a CE 5.0 device from Studio '08 on Vista quite regularly. I use the same general outline of steps (though i do use a tool that automates the process).
464,000
464,156
Simple Dynamic Graph Display for C++
I am looking for a simple graph layout library for C++. I want to embed the library into our visualizer based on wxWidgets. In summary, I am looking for something like graphviz, except dynamic - that is when an event occurs, only the change in graph needs to be loaded, not the complete display. There is dynagraph, but it seems a dead project. I have previously been suggested to use VTK - but it is a heavyweight. I am looking for open source, non-copyleft kind of library available for commercial use (GPL is out, LGPL should be ok). I am open to suggestions that google won't give.
The layout that Graphviz generates is based on the global structure - any single addition can dramatically change the output (unless you're using fixed coordinates, in which case you probably wouldn't be asking this question). Basically, if you want automatic placement of elements, you need to accept one of these solutions: When a new element is placed, a physics simulation is run in realtime, causing nodes to bounce around wildly until they settle into their new locations. This will be slow, but it will show "pleasing" changes. When a new element is placed, the entire graph is re-drawn (physics/whatever is hidden, but the entire thing gets modified). This will be faster due to not having to redraw, but the relative locations of nodes can be completely different. When a new element is placed, the existing elements are not modified. After enough dynamic updates, your graph is going to look like crap, because automatic placement is a global optimization problem. Sorry I can't help with your question, but maybe this helps to explain why what you're looking for may simply not exist (or be any good).
464,143
464,159
Why doesnt Multi Args in constructor work under linux?
For my exception class i have a constructor that has multi arguments (...) which works fine under windows, how ever, under linux it compiles fine but refuses to link to it. Why does this not work under linux? here is an example: class gcException { public: gcException() { //code here } gcException(uint32 errId, const char* format = NULL, ...) { //code here } } enum { ERR_BADCURLHANDLE, }; . Edit So when i call it like so: if(!m_pCurlHandle) throw gcException(ERR_BADCURLHANDLE); I get this compile error: error: no matching function for call to ‘gcException::gcException(gcException)’ candidates are: gcException::gcException(const gcException*) gcException::gcException(gcException*) gcException::gcException(gcException&)
It compiles and links just fine. I expanded your test code to a full "program": class gcException { public: gcException() { } gcException(int errId, const char* format, ...) { } }; int main() { new gcException(1, "foo", "bar", "baz"); } And then g++ -Wall test.cpp ran without errors. According to g++ -v, I have gcc version 4.3.2 (Debian 4.3.2-1.1). Does my quick example compile for you? (Did you maybe accidentally compile — or link — with gcc instead of g++?)
464,560
464,595
How to use #include directive correctly?
Is there any material about how to use #include correctly? I didn't find any C/C++ text book that explains this usage in detail. In formal project, I always get confused in dealing with it.
Check Large-Scale C++ Software Design from John Lakos if you have the money. Google C++ coding guidelines also have some OK stuff. Check Sutter Herb materials online (blog) as well. Basically you need to understand where include headers are NOT required, eg. forward declaration. Also try to make sure that include files compiles one by one, and only put #includes in h files when it's a must (eg. templates).
464,618
464,676
What's the equivalent of Windows' QueryPerformanceCounter on OSX?
I'm porting a library from Windows to *NIX (currently OSX), does anyone now what function can I use instead of Microsoft's QueryPerformanceCounter and QueryPerformanceFrequency?
http://www.tin.org/bin/man.cgi?section=3&topic=clock_gettime (and the other functions mentioned there) - it's Posix! Will fall back to worse counters if HPET is not existent. (shouldn't be a problem though) http://en.wikipedia.org/wiki/High_Precision_Event_Timer Resolution should be about +10Mhz.
464,675
465,500
CListCtrl - how to enable multiple selection
I am creating a MFC application for Windows Mobile and don't know how to enable multiple selection for List Control (CListCtrl). In properties panel Single Selection is set to False but still can't select multiple items. Any idea?
I have never targeted Windows Mobile but you might try the following: list.ModifyStyle(LVS_SINGLESEL, 0);
464,788
464,796
Port Mingw32 based code to msvc2008
We recently had a new requirement to use the phonon component of Qt, which on windows requires Visual Studio. I installed VS2008 and ran a compile. There are a stack of problems due to make not working anything like nmake. Since I need to maintain cross-platform I want to test which compiler is being used so that I can make changes as required. An example is that the PRETTY_FUNCTION is a g++ macro with FUNCDNAME being the VC equivalent. How do I test which compiler I am using to determine which macro to call?
Use the _MSC_VER macro. If it is defined, you're using Visual Studio: #ifdef _MSC_VER ... MSVC code ... #else ... other compiler ... #endif
464,843
464,916
C++ 3D Model Animation libraries?
I have my own game engine using C++ and OpenGL, but I have models with individual pieces that can be moved, and Im not sure how to animate them without hardcoding it. Are there any libraries that would provide a solution via scripts or IK or some other animation technique without resorting to a game engine such as Ogre?
Cal3d could be an option. Skinned character animation without needing to import a whole engine.
465,345
466,874
How do you create a COM DLL in Visual Studio 2008?
It's been ages since I've written a COM dll. I've made a couple of classes now, that inherit from some COM interfaces, but I want to test it out. I know I have to put a GUID somewhere and then register it with regsvr32, but what are the steps involved? Edit: Sorry, forgot to mention I'm using C++.
To create a new ATL COM project you can proceed as follow: File/New Project Visual C++/ATL/ATL Project Customize it settings, and press finish when done You have created a new dll, but it is empty, to add a COM object you can do this: Project/Add Class Visual C++/ATL/ATL simple object, press add Give the name you want (like MyObject), and press finish to add it If you want that an object implement an interface In the class view select the object class (CMyObject) Right click/Add/Implement Interface... You can select which Interface will implement From an .idl file already in your projects files From a .tlb/.dll/.exe which have a type library embedded From an object already registered When done press finish PS: It is much easier to create a new ATL project with the same name in a different folder, and add the files you have customized. The wizard does several tasks and create several customized files. For larger projects that are difficult to add file by file, I do the same but instead of adding my files to the new project I start copying the settings from the new projects to the old one, and adding any additional file that the wizard has created and fixing headers like stdafx.h to merge the new settings. PPS: If you want that your dll to support MFC, instead of selecting ATL Project you have to select MFC/MFC Dll. When you add the ATL Simple Object the wizard will ask to add ATL support to the project.
465,388
465,403
C++. Is it possible that a RNG gives different random variable in two different machines using the same seed?
I have this long and complex source code that uses a RNG with a fix seed. This code is a simulator and the parameters of this simulator are the random values given by this RNG. When I execute the code in the same machine, no matter how many attempts I do the output is the same. But when I execute this code on two different machines and I compare the outputs of both the machines, they are different. Is it possible that two different machines gives somehow different output using the same random number generator and the same seed? The compiler version, the libraries and the OS are the same.
It is certainly possible, as the RNG may be combining machine specific data with the seed, such as the network card address, to generate the random number. It is basically implementation specific.
465,517
465,594
overloaded increment's return value
In his The C++ Programming Language Stroustrup gives the following example for inc/dec overloading: class Ptr_to_T { T* p; T* array ; int size; public: Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p Ptr_to_T(T* p); // bind to single object, initial value p Ptr_to_T& operator++(); // prefix Ptr_to_T operator++(int); // postfix Ptr_to_T& operator--(); // prefix Ptr_to_T operator--(int); // postfix T&operator*() ; // prefix } Why prefix operators return by reference while postfix operators return by value? Thanks.
To understand better, you have to imagine (or look at) how are these operators implemented. Typically, the prefix operator++ will be written more or less like this: MyType& operator++() { // do the incrementation return *this; } Since this has been modified "in-place", we can return a reference to the instance in order to avoid a useless copy. Now, here's the code for the postfix operator++: MyType operator++(int) { MyType tmp(*this); // create a copy of 'this' ++(*this); // use the prefix operator to perform the increment return tmp; // return the temporary } As the postfix operator returns a temporary, it has to return it by value (otherwise, you'll get a dangling reference). The C++ Faq Lite also has a paragraph on the subject.
465,693
465,744
What garbage collectors are there available for C++?
What garbage collectors are there available for C++? Are you using any of them? With what results?
The Boost library includes some shared_ptr stuff that basically acts as a reference counting garbage collector. If you embrace the RAII principle of C++ design, that and auto_ptr will fill your need for a "garbage collector".
466,143
466,246
QCompleter and QLineEdit for multiple words
Is there any way to have the QCompleter to act like an autocomplete for multiple words? Someone has any idea how to do it?
I don't know if I understand correctly: QStringList wordList; wordList << "alpha and beta" << "omega" << "omicron" << "zeta"; QCompleter *completer = new QCompleter(wordList, this); completer->setCaseSensitivity(Qt::CaseInsensitive); QLineEdit *lineEdit = new QLineEdit(this); lineEdit->setCompleter(completer); If you type alp then you get the completion "alpha and beta" which is more than one word. There is no limit. Update after clarifications: Seems that what is requested is starting a new autocompletion after a delimiter value. In the current case this delimiter will be a space. An equivalent example would be the tree model completer from the Qt examples. This example illustrates how to solve the same situation.
466,285
470,268
Availability of #include <map> with xlC on AIX 4.3
Is there a version of xlC/VACPP available for AIX 4.3, which does not choke when given following source: #include <map> int main(void) { return 0; } If yes, is it still available anywhere?
You might want to try using STLport as a replacement for the STL shipped with the compiler.
466,377
466,389
How to detect what CPU is being used during runtime?
How can I detect which CPU is being used at runtime ? The c++ code needs to differentiate between AMD / Intel architectures ? Using gcc 4.2.
If you're on Linux (or on Windows running under Cygwin), you can figure that out by reading the special file /proc/cpuinfo and looking for the line beginning with vendor_id. If the string is GenuineIntel, you're running on an Intel chip. If you get AuthenticAMD, you're running on an AMD chip. void get_vendor_id(char *vendor_id) // must be at least 13 bytes { FILE *cpuinfo = fopen("/proc/cpuinfo", "r"); if(cpuinfo == NULL) ; // handle error char line[256]; while(fgets(line, 256, cpuinfo)) { if(strncmp(line, "vendor_id", 9) == 0) { char *colon = strchr(line, ':'); if(colon == NULL || colon[1] == 0) ; // handle error strncpy(vendor_id, 12, colon + 2); fclose(cpuinfo); return; } } // if we got here, handle error fclose(cpuinfo); } If you know you're running on an x86 architecture, a less portable method would be to use the CPUID instruction: void get_vendor_id(char *vendor_id) // must be at least 13 bytes { // GCC inline assembler __asm__ __volatile__ ("movl $0, %%eax\n\t" "cpuid\n\t" "movl %%ebx, %0\n\t" "movl %%edx, %1\n\t" "movl %%ecx, %2\n\t" : "=m"(vendor_id), "=m"(vendor_id + 4), "=m"(vendor_id + 8) // outputs : // no inputs : "%eax", "%ebx", "%edx", "%ecx", "memory"); // clobbered registers vendor_id[12] = 0; } int main(void) { char vendor_id[13]; get_vendor_id(vendor_id); if(strcmp(vendor_id, "GenuineIntel") == 0) ; // it's Intel else if(strcmp(vendor_id, "AuthenticAMD") == 0) ; // it's AMD else ; // other return 0; }
466,488
466,531
Printing detailed debugging output easily?
I'm basically looking for a way to automate typing stuff like the following: cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl; Something like: PRINTDBG(a[x][y]); Ideally this would also work for PRINTDBG(func(arg1, arg2)); and even PRINTDBG(if(condition) func(foo);); (which would print e.g. "if(false) func(5)"). Nonportable hacks welcome too :) (no, using a debugger isn't the same, it's much less flexible and I find it confusing)
This is, in the way you want it, not possible. If you have if(condition) func(foo); given to a macro, it can stringize that stuff, and it will print if(condition) func(foo);, but not with the actual values of the variables substituted. Remember the preprocessor doesn't know about the structure about that code. For debugging, i would use some type-safe printf variant like boost.format or some home brew printf with boost.fusion, which make the job of printing stuff like that much more easy: dprintf("a[%][%] = %", (x, y, a[x][y]));