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
1,291,226
1,291,304
What is an SDK? (C++)
Just in general terms, for a noobie. I apparently need an 'SDK' to install something; what is this?
An SDK is a set of libraries which hold reusable code that you in turn use to develop applications. Whether those applications will run in Windows, on an XBOX, and iPhone, in a Flash application, etc. determine what SDK you should be using. Take the iPhone for example. To write an iPhone application, you write code in a language called Objective-C (which looks and feels just like C, but with Smalltalk's object-model). Anyway, every time you write an app, you don't need to rewrite the code that draws text on the actual screen or registers the actual screen-touches. Instead, Apple provides the code that all application developers will need to do simple things. Likewise, if you're writing for Windows, there are libraries to do things like draw an actual window, or connect to the network stack. All of these common libraries, along with some other tools, make up an SDK. For C++, you will probably see a lot of mention of Boost. This is not an SDK, but rather a set of libraries that contain code that a lot of other developers find useful. What platform are you trying to write for? Are you just getting into C++ in Windows and looking to get started? Are you trying to write a game for some console?
1,291,324
1,291,519
"Is there a better way?" Error 12029 with wininet on Windows Vista
I kept recieving error 12029 (ERROR INTERNET CANNOT CONNECT, The attempt to connect to the server failed.) when using the the MFC wininet classes on Windows Vista. The cause of the error was due to Windows Defender. Is there a better way to get around this than completely turning off Windows Defender? I tried turning off "real time protection" to no avail, I had to completely turn WD off to stop the 12029 errors. If there is no better solution hopefully someone else with the same issue will see this question and be able to fix thier own problem. I searched the intertubes high and low and didn't find any crossreferences between wininet error 12029 and WD. My code for reference ::CInternetSession session; ::CHttpConnection* connection = session.GetHttpConnection(L"twitter.com",80,m_csUserName,m_csPassword); ::CHttpFile* httpfile = connection->OpenRequest(CHttpConnection::HTTP_VERB_GET,L"/account/verify_credentials.xml"); httpfile->SendRequest();
If Windows Defender displays a warning message after blocking your program, you should have the option to add your program to a list of "allowed items" which will allow it to run unencumbered while real time protection remains enabled. Admittedly, this is only a viable option if you are working with non-production/personal code (and if Defender is even displaying a warning message at all). That said, it is possible that Defender has detected some possible risk based on the way you are using the wininet library -- would it be possible to use lower-level sockets instead? If this is the only network code you use, it would be easy to replicate it through the generic winsock library and there's a good chance that Defender would be much less inclined to block your program if you use it instead of wininet. Edit: In addition to testing the MFC fragment separately as I suggested in the comments below, it may be worthwhile to try it the standard WinAPI way -- the idea being, if there's something wrong with the wininet library on your computer, this code should also fail to connect: int read = 0; char* str = "*/*", buff[1024] = {}; HINTERNET inet = InternetOpen("GRB", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); if (!(inet=InternetConnect(inet, "twitter.com", 80, "username", "password", INTERNET_SERVICE_HTTP, 0, 0))) cout << "conn failed" << endl; if (!(inet=HttpOpenRequest(inet, "GET", "/account/verify_credentials.xml", NULL, NULL, (const char**)&str, 0, 0))) cout << "open failed" << endl; if (!HttpSendRequest(inet, NULL, 0, NULL, 0)) cout << "send failed" << endl; InternetReadFile(inet, buff, 1023, (DWORD*)&read); cout << buff << endl; system("pause"); (designed to be a console program, be sure to include the correct headers/libraries)
1,291,338
1,300,352
Write unicode string into file with CodeGear C++ Builder 2009
I have just switched from Builder 6 to Builder 2009 and have a question. How can I write unicode string to a file? TBytes Preamble1 = TEncoding::Unicode->GetPreamble(); UnicodeString str1("string1"); int len = TEncoding::Unicode->GetByteCount(str1); FileWrite( iFile,&Preamble1[0],Preamble1.Length ); FileWrite( iFile,str1.c_str(),len ); This is what I am doing now but I guess there should be some native way. Btw, is it OK to get Preamble once and assume that during the application lifetime it does not change? From available documentation for UnicodeString it seems that it is always UTF-16 LE
My first question would be "What kind of file"? Assuming it's a text file rather than binary, what kind of encoding do you want on the output? UTF-8 is usually a good choice, because it's supported by stuff like notepad, and for normal "Latin" characters, there's no overhead. Personally, to write 'simple' text files, I just add strings to a TStringList and then use SaveToFile method. TStringList *list = new TStringList; list->Add(str1); list->Add(str2); ... list->SaveToFile(filename, TEncoding::UTF8);
1,291,446
1,291,493
Visual C++ versions of GCC functions
Are there Visual C++ versions of the following (in GCC)? __builtin_return_address __builtin_frame_address Reference - http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html If not, is there a way to emulate them? Thanks.
Here is a full list of the available Visual Studio 2008 Compiler Intrinsics. One of the ones you are specifically looking for here is _ReturnAddress... still looking for the other. For walking the stack (and getting frame pointers), read the details on the Visual Leak Detector stack walking mechanism, which uses StackWalk64 internally.
1,291,594
1,295,828
Using libs/dlls compiled in Linux/MinGW in Visual Studio
Update: I get this warning when compiling: multiple '.text' sections found with different attributes Hi, I've compiled some libraries (.a and .dll) in Linux using the MinGW Cross Compiler. I can successfully link against them (.a) in Visual Studio 2008. However, when it runs (using .dll), it terminates with the address pointer pointing at empty memory addresses. Is there a way/a list of things to do that will allow me to use those libraries successfully in VC08? The cross compiler generates *.dll.a *.dll Thanks
Found it. http://www.mingw.org/wiki/MSVC_and_MinGW_DLLs You have to have a def file and use the VC's lib tool to generate an import library.
1,292,138
1,292,157
When to use extern "C" in C++?
Possible Duplicate: Why do we need extern “C”{ #include <foo.h> } in C++? I have often seen programs coded like: extern "C" bool doSomeWork() { // return true; } Why do we use an extern "C" block? Can we replace this with something in C++? Is there any advantage to using extern "C"? I do see a link explaining this but why do we need to compile something in C when we already have C++?
extern "C" makes names not mangled. It used when: We need to use some C library in C++ extern "C" int foo(int); We need export some C++ code to C extern "C" int foo(int) { something; } We need an ability to resolve symbol in shared library -- so we need to get rid mangling extern "C" int foo(int) { something; } /// typedef int (*foo_type)(int); foo_type f = (foo_type)dlsym(handle,"foo")
1,292,241
1,292,387
Creating custom dictionaries in aspell with the C API
I am using aspell in my application for spell checking (a c/c++ app), and I want to use it to find best alternatives in a custom work list. I don't want to use a standard dictionary, as I only want to find words in my word list. I can find ways of adding words to a dictionary (aspell_speller_add_to_personal and aspell_speller_add_to_session), but I don't know how to start with an empty dictionary that I can then populate at run time. Has anybody done this, or know how to do it? Alternatively, any recommendations for algorithms for choosing a "best match" in a word list?
I did this about three years ago. It was in a convoluted way that included creating a dictionary data structure from an existing file, deleting it and adding words using aspeller::Dictionary::add(). It was tough. If you do not have to use aspell, you may try hunspell, which may or may not be easier to customize. See also Peter Norvig's Great Paper about writing a spelling corrector.
1,292,297
1,292,669
boost::array not compiling on VS 2005
Sorry this is probably a stupid question, as I couldn't find anything at all on google on the subject. Anyways I'm trying to compile some source code, that uses boost::array with visual studio 2005, as a Win32 console application (not clr), however for some reason that escapes me Visual Studio still considers the word array a keyword, so it chokes on all the boost::array<>'s in the code with errors like this: Error 1 error C2039: 'array' : is not a member of 'boost' d:\projects\libraries\boost_1_36_0-1\boost_1_36_0\boost\asio\buffer.hpp 809 I'm quite sure there is something terribly stupid and probably obvious I'm missing as no one in the world seems to have this problem (according to Google's results I found)
This simple program compiled and worked perfectly in my VC++ 2005: #include <iostream> #include <boost/array.hpp> int main() { const int size = 3; boost::array<double,size> myArray; myArray[0] = 23.43f; myArray[1] = 24.00f; myArray[2] = 23.50f; double sum = 0.0; for (size_t i = 0; i < myArray.size(); ++i) { sum += myArray[i]; } std::cout << "sum=" << sum << '\n'; return 0; } Could you post a small code snippet that fails?
1,292,426
1,292,443
Is there any well-known paradigm for iterating enum values?
I have some C++ code, in which the following enum is declared: enum Some { Some_Alpha = 0, Some_Beta, Some_Gamma, Some_Total }; int array[Some_Total]; The values of Alpha, Beta and Gamma are sequential, and I gladly use the following cycle to iterate through them: for ( int someNo = (int)Some_Alpha; someNo < (int)Some_Total; ++someNo ) {} This cycle is ok, until I decide to change the order of the declarations in the enum, say, making Beta the first value and Alpha - the second one. That invalidates the cycle header, because now I have to iterate from Beta to Total. So, what are the best practices of iterating through enum? I want to iterate through all the values without changing the cycle headers every time. I can think of one solution: enum Some { Some_Start = -1, Some_Alpha, ... Some_Total }; int array[Some_Total]; and iterate from (Start + 1) to Total, but it seems ugly and I have never seen someone doing it in the code. Is there any well-known paradigm for iterating through the enum, or I just have to fix the order of the enum values? (let's pretend, I really have some awesome reasons for changing the order of the enum values)...
enum Some { Some_first_ = 0, Some_Alpha = Some_first_, .... Some_last_ }; Doing such you can grant first & last never changes order
1,292,511
1,292,745
Using stable_sort() to sort doubles as ints
I have a huge array of ints that I need to sort. The catch here is that each entry in the list has a number of other associated elements in it that need to follow that int around as it gets sorted. I've kind of solved this problem by changing the sorting to sort doubles instead of ints. I've tagged each number before it was sorted with a fractional part denoting that value's original location before the sort, thus allowing me to reference it's associated data and allowing me to efficiently rebuild the sorted list with all the associated elements. My problem is that I want to sort the double values by ints using the function stable_sort(). I'm referring to this web page: http://www.cplusplus.com/reference/algorithm/stable_sort/ However, since I'm a new programmer, i don't quite understand how they managed to get the sort by ints to work. What exactly am i supposed to put into that third argument to make the function work? (i know i can just copy and paste it and make it work, but i want to learn and understand this too). Thanks, -Faken Edit: Please note that I'm a new programmer who has had no formal programming training. I'm learning as i go so please keep your explanations as simple and as rudimentary as possible. In short, please treat me as if i have never seen c++ code before.
Since you say you're not familiar with vectors (you really should learn STL containers ASAP, though), I assume you're playing with arrays. Something along these lines: int a[] = { 3, 1, 2 }; std::stable_sort(&a[0], &a[3]); The third optional argument f of stable_sort is a function object - that is, anything which can be called like a function by following it with parentheses - f(a, b). A function (or rather a pointer to one) is a function object; other kinds include classes with overloaded operator(), but for your purposes a plain function would probably do. Now you have your data type with int field on which you want to sort, and some additional data: struct foo { int n; // data ... }; foo a[] = { ... }; To sort this (or anything, really), stable_sort needs to have some way of comparing any two elements to see which one is greater. By default it simply uses operator < to compare; if the element type supports it directly, that is. Obviously, int does; it is also possible to overload operator< for your struct, and it will be picked up as well, but you asked about a different approach. This is what the third argument is for - when it is provided, stable_sort calls it every time it needs to make a comparison, passing two elements as the arguments to the call. The called function (or function object, in general) must return true if first argument is less than second for the purpose of sorting, or false if it is greater or equal - in other words, it must work like operator < itself does (except that you define the way you want things to be compared). For foo, you just want to compare n, and leave the rest alone. So: bool compare_foo_n(const foo& l, const foo& r) { return l.n < r.n; } And now you use it by passing the pointer to this function (represented simply by its name) to stable_sort: std::stable_sort(&a[0], &a[3], compare_foo_n);
1,292,718
1,292,773
about the cost of virtual function
If I call a virtual function 1000 times in a loop, will I suffer from the vtable lookup overhead 1000 times or only once?
The Visual C++ compiler (at least through VS 2008) does not cache vtable lookups. Even more interestingly, it doesn't direct-dispatch calls to virtual methods where the static type of the object is sealed. However, the actual overhead of the virtual dispatch lookup is almost always negligible. The place where you sometimes do see a hit is in the fact that virtual calls in C++ cannot be replaced by direct calls like they can in a managed VM. This also means no inlining for virtual calls. The only true way to establish the impact for your application is using a profiler. Regarding the specifics of your original question: if the virtual method you are calling is trivial enough that the virtual dispatch itself is incurring a measurable performance impact, then that method is sufficiently small that the vtable will remain in the processor's cache throughout the loop. Even though the assembly instructions to pull the function pointer from the vtable are executed 1000 times, the performance impact will be much less than (1000 * time to load vtable from system memory).
1,292,786
1,292,938
Is Updating double operation atomic
In Java, updating double and long variable may not be atomic, as double/long are being treated as two separate 32 bits variables. http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28733 In C++, if I am using 32 bit Intel Processor + Microsoft Visual C++ compiler, is updating double (8 byte) operation atomic? I cannot find much specification mention on this behavior. When I say "atomic variable", here is what I mean : Thread A trying to write 1 to variable x. Thread B trying to write 2 to variable x. We shall get value 1 or 2 out from variable x, but not an undefined value.
This is hardware specific and depends an the architecture. For x86 and x86_64 8 byte writes or reads are guaranteed to be atomic, if they are aligned. Quoting from the Intel Architecture Memory Ordering White Paper: Intel 64 memory ordering guarantees that for each of the following memory-access instructions, the constituent memory operation appears to execute as a single memory access regardless of memory type: Instructions that read or write a single byte. Instructions that read or write a word (2 bytes) whose address is aligned on a 2 byte boundary. Instructions that read or write a doubleword (4 bytes) whose address is aligned on a 4 byte boundary. Instructions that read or write a quadword (8 bytes) whose address is aligned on an 8 byte boundary. All locked instructions (the implicitly locked xchg instruction and other read-modify-write instructions with a lock prefix) are an indivisible and uninterruptible sequence of load(s) followed by store(s) regardless of memory type and alignment.
1,292,927
1,293,103
wait for works item to complete pooled using QueueUserWorkItem (not .NET)
I have some work items pooled using the legacy QueueUserWorkItem function (I need to support OSs earlier than vista, so for( <loop thru some items >) { QueueUserWorkItem( ) } I need to wait on these before proceeding to the next step. I've seen several similar answers...but they are in .NET. I'm thinking of using a storing an Event for each item and waiting on them(gasp!), but are there other better, lightweight ways? (no kernel locks) Clarification: I know of using Events. I'm interested in solutions that don't require a kernel-level lock.
AFAIK the only ways you can do this is to have a counter that is InterlockIncrement'ed as each task finishes. You can then either do a while( counter < total ) Sleep( 0 ); of the task can signal an event (or other sync object) and you can do the following while( count < total ) WaitForSingleObject( hEvent, INFINITE ); The second method will mean that the main thread uses less processing time. Edit: TBH the only way to avoid a kernel lock is to spin lock and that will mean you'll have one core wasting time that could otherwise be used to process your work queue (or indeed anything else). If you REALLY must avoid a kernel lock then spin lock with a Sleep( 0 ). However I'd definitely recommend just using a kernel lock, get the extra CPU time back for doing worthwhile processing and stop worrying about a 'non' problem.
1,292,995
1,294,006
writing files and dirs using C++
I'm working on a program that creates 2000 directories and puts a file in each (just a 10KB or so file). I am using mkdir to make the dirs and ofstream (i tried fopen as well) to write the files to a solid state drive (i'm doing speed tests for comparison). When I run the code the directories are created fine but the files stop writing after 1000 or so have been written. I've tried putting a delay before each write in case it was some kind of overload and also tried using fopen instead of ofstream but it always stops writing the files around the 1000th file mark. this is the code that writes the files and exits telling me which file it failed on. fsWriteFiles.open(path, ios::app); if(!fsWriteFiles.is_open()) { cout << "Fail at point: " << filecount << endl; return 1; } fsWriteFiles << filecontent; fsWriteFiles.close(); Has anyone had any experience of this or has any theories? Here's the full code: This code creates a 2 digit hex directory from a random number then a 4 digit hex directory from a random number then stores a file in that directory. It exits with a 'fail at point' (a cout I've added) after writing 1000ish files. This indicates that it cannot create a file, but it should have already checked that the file does not exist. Sometimes it fails on 0 having hit the second from bottom line (else clause for file already existing). any help appreciated, I feel that it is to do with the files i'm trying to create already existing but that have somehow slipped by my file existence check. Is there a way to get an error message for a failed file creation attempt? int main() { char charpart1[3] = ""; char charpart3[5] = ""; char path[35] = ""; int randomStore = 0; //Initialize random seed srand(time(NULL)); struct stat buffer ; //Create output file streams ofstream fsWriteFiles; ifstream checkforfile; //Loop X times int dircount = 0; while(dircount < 2000) { path[0] = '\0'; //reset the char array that holds the path randomStore = rand() % 255; sprintf(charpart1, "%.2x", randomStore); randomStore = rand() % 65535; sprintf(charpart3, "%.4x", randomStore); //Check if top level dir exists, create if not strcat(path, "fastdirs/"); strcat(path, charpart1); DIR *pdir=opendir(path); //If the dir does not exist create it with read/write/search permissions for owner // and group, and with read/search permissions for others if(!pdir) mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); //Check if 3rd level dir exists, create if not strcat(path, "/"); strcat(path, charpart3); DIR *pdir3=opendir(path); if(!pdir3) mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); strcat(path, "/"); strcat(path, charpart3); strcat(path, ".txt"); //Write the file if it does not already exist checkforfile.open(path, fstream::in); if (checkforfile.is_open() != true) { fsWriteFiles.open(path, ios::app); if(!fsWriteFiles.is_open()) { cout << "Fail at point: " << dircount << "\n" << endl; return 1; } fsWriteFiles << "test"; fsWriteFiles.flush(); fsWriteFiles.close(); dircount ++; //increment the file counter } else { cout << "ex"; checkforfile.close(); } } }
You open directories with opendir() but never close them with closedir() - I suspect there is a resource limit there too.
1,293,231
1,293,274
stl ordering - strict weak ordering
Why does STL work with a comparison function that is strict weak ordering? Why can't it be partial ordering?
A partial order would not be sufficient to implement some algorithms, such as a sorting algorithm. Since a partially ordered set does not necessarily define a relationship between all elements of the set, how would you sort a list of two items that do not have an order relationship within the partial order?
1,293,326
1,293,421
Deleting pointer sometimes results in heap corruption
I have a multithreaded application that runs using a custom thread pool class. The threads all execute the same function, with different parameters. These parameters are given to the threadpool class the following way: // jobParams is a struct of int, double, etc... jobParams* params = new jobParams; params.value1 = 2; params.value2 = 3; int jobId = 0; threadPool.addJob(jobId, params); As soon as a thread has nothing to do, it gets the next parameters and runs the job function. I decided to take care of the deletion of the parameters in the threadpool class: ThreadPool::~ThreadPool() { for (int i = 0; i < this->jobs.size(); ++i) { delete this->jobs[i].params; } } However, when doing so, I sometimes get a heap corruption error: Invalid Address specified to RtlFreeHeap The strange thing is that in one case it works perfectly, but in another program it crashes with this error. I tried deleting the pointer at other places: in the thread after the execution of the job function (I get the same heap corruption error) or at the end of the job function itself (no error in this case). I don't understand how deleting the same pointers (I checked, the addresses are the same) from different places changes anything. Does this have anything to do with the fact that it's multithreaded? I do have a critical section that handles the access to the parameters. I don't think the problem is about synchronized access. Anyway, the destructor is called only once all threads are done, and I don't delete any pointer anywhere else. Can pointer be deleted automatically? As for my code. The list of jobs is a queue of a structure, composed of the id of a job (used to be able to get the output of a specific job later) and the parameters. getNextJob() is called by the threads (they have a pointer to the ThreadPool) each time they finished to execute their last job. void ThreadPool::addJob(int jobId, void* params) { jobData job; // jobData is a simple struct { int, void* } job.ID = jobId; job.params = params; // insert parameters in the list this->jobs.push(job); } jobData* ThreadPool::getNextJob() { // get the data of the next job jobData* job = NULL; // we don't want to start a same job twice, // so we make sure that we are only one at a time in this part WaitForSingleObject(this->mutex, INFINITE); if (!this->jobs.empty()) { job = &(this->jobs.front()); this->jobs.pop(); } // we're done with the exclusive part ! ReleaseMutex(this->mutex); return job; }
Let's turn this on its head: Why are you using pointers at all? class Params { int value1, value2; // etc... } class ThreadJob { int jobID; // or whatever... Params params; } class ThreadPool { std::list<ThreadJob> jobs; void addJob(int job, const Params & p) { ThreadJob j(job, p); jobs.push_back(j); } } No new, delete or pointers... Obviously some of the implementation details may be cocked, but you get the overall picture.
1,293,708
1,293,887
Compile error using boost::concept_check
I'm trying to compile simple example to use the boost concept_check Code is as follow: #include <vector> #include <complex> #include <algorithm> #include <boost/iterator.hpp> #include <boost/concept_check.hpp> template <class foo> void my_do_sort(std::vector<foo>& v) { BOOST_CONCEPT_ASSERT((RandomAccessIterator<foo>)); std::stable_sort(v.begin(),v.end()) } int main() { std::vector<std::complex<double> > v; v.push_back(std::complex<double>(1,3)); v.push_back(std::complex<double>(2,4)); my_do_sort(v); } I then get the following error: g++ -I~/tmp/BOOST/boost_1_39_0 -g3 -ggdb -pedantic -pedantic-errors -Wall -Werror -O0 --save-temps con1.cpp -o con1 con1.cpp: In function 'void my_do_sort(std::vector<foo, std::allocator<_CharT> >&)': con1.cpp:11: error: `*' cannot appear in a constant-expression con1.cpp:11: error: a call to a constructor cannot appear in a constant-expression con1.cpp:11: error: template argument 1 is invalid con1.cpp:11: error: template argument 1 is invalid con1.cpp:11: error: invalid type in declaration before ';' token make: *** [con1] Error 1 Thanks
This was just compilation issue. I had to use boost namespace.
1,293,889
1,293,953
Microsoft _stprintf warning
Why I get the following warning for the following code :) Code: _stprintf(m_szFileNamePath,_T("%s"),strFileName); warning C4996: '_swprintf': swprintf has been changed to conform with the ISO C standard, adding an extra character count parameter. To use traditional Microsoft swprintf, set _CRT_NON_CONFORMING_SWPRINTFS. I know _strprintf is a macro which if _UNICODE is defined will evaluate to _swprintf else it will be sprintf. Now what is this _swprintf. There is a function swprintf, but why is _stprintf evaluating to _swprintf instead of swprintf. What is the difference b/w the _xxx and xxx functions? EDIT: Okay there are two definitions for the UNICODE version of _stprintf, which one is included? The one in tchar.h or strsafe.h?
http://msdn.microsoft.com/en-us/library/ybk95axf%28VS.80%29.aspx swprintf is a wide-character version of sprintf; the pointer arguments to swprintf are wide-character strings. Detection of encoding errors in swprintf may differ from that in sprintf. swprintf and fwprintf behave identically except that swprintf writes output to a string rather than to a destination of type FILE, and swprintf requires the count parameter to specify the maximum number of characters to be written. The versions of these functions with the _l suffix are identical except that they use the locale parameter passed in instead of the current thread locale. In Visual C++ 2005, swprintf conforms to the ISO C Standard, which requires the second parameter, count, of type size_t. To force the old nonstandard behavior, define _CRT_NON_CONFORMING_SWPRINTFS. In a future version, the old behavior may be removed, so code should be changed to use the new conformant behavior.
1,293,933
1,298,323
Synchronizing access to variable
I need to provide synchronization to some members of a structure. If the structure is something like this struct SharedStruct { int Value1; int Value2; } and I have a global variable SharedStruct obj; I want that the write from a processor obj.Value1 = 5; // Processor B to be immediately visible to the other processors, so that when I test the value if(obj.Value1 == 5) { DoSmth(); } // Processor A else DoSmthElse(); to get the new value, not some old value from the cache. First I though that if I use volatile when writing/reading the values, it is enough. But I read that volatile can't solve this kind o issues. The members are guaranteed to be properly aligned on 2/4/8 byte boundaries, and writes should be atomic in this case, but I'm not sure how the cache could interfere with this. Using memory barriers (mfence, sfence, etc.) would be enough ? Or some interlocked operations are required ? Or maybe something like lock mov addr, REGISTER ? The easiest would obviously be some locking mechanism, but speed is critical and can't afford locks :( Edit Maybe I should clarify a bit. The value is set only once (behaves like a flag). All the other threads need just to read it. That's why I think that it may be a way to force the read of this new value without using locks. Thanks in advance!
All the other answers here seem to hand wave about the complexities of updating shared variables using mutexes, etc. It is true that you want the update to be atomic. And you could use various OS primitives to ensure that, and that would be good programming style. However, on most modern processors (certainly the x86), writes of small, aligned scalar values is atomic and immediately visible to other processors due to cache coherency. So in this special case, you don't need all the synchronizing junk; the hardware does the atomic operation for you. Certainly this is safe with 4 byte values (e.g., "int" in 32 bit C compilers). So you could just initialize Value1 with an uninteresting value (say 0) before you start the parallel threads, and simply write other values there. If the question is exiting the loop on a fixed value (e.g., if value1 == 5) this will be perfectly safe. If you insist on capturing the first value written, this won't work. But if you have a parallel set of threads, and any value written other than the uninteresting one will do, this is also fine.
1,293,951
1,294,002
Mix of template and struct
I have a template class defined as follow : template <class T1, class T2> class MyClass { }; In this class, I need a struct that contains one member of type T1. How can I do that ? I tried the following, but it didn't work : template <class T1, class T2> class MyClass { typedef struct { T1 templateMember; // rest of members } myStruct; // rest of class definition }; EDIT: As requested, I use VS2008 and get the following error : 'MyClass<T1,T2>::myStruct' uses undefined class 'T1'
Just remove typedef: template <class T1, class T2> class MyClass { struct myStruct{ T1 templateMember; // rest of members } ; };
1,294,215
1,294,259
Member function pointer calls copy constructor?
I'm trying to create a lookup table of member functions in my code, but it seems to be trying to call my copy constructor, which I've blocked by extending an "uncopyable" class. What I have is something like the following. enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS }; class Foo { fun1(Bar b){ ... } fun2(Bar b){ ... } ... void (Foo::*lookup_table[NUM_FUNS])(Bar b); Foo(){ lookup_table[FUN1_IDX] = &Foo::fun1; lookup_table[FUN2_IDX] = &Foo::fun2; } void doLookup(int fun_num, Bar b) { (this->*lookup_table[fun_num])(b); } }; The error is that the '(this->...' line tries to call the copy constructor, which is not visible. Why is it trying to do this, and what do I have to change so it won't?
Make them reference parameters. enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS }; class Foo { fun1(Bar &b){ ... } fun2(Bar &b){ ... } ... void (Foo::*lookup_table[NUM_FUNS])(Bar &b); Foo(){ lookup_table[FUN1_IDX] = &Foo::fun1; lookup_table[FUN2_IDX] = &Foo::fun2; } void doLookup(int fun_num, Bar &b) { (this->*lookup_table[fun_num])(b); } }; In C++, otherwise such plain parameters don't just reference objects, but they are those objects themselves. Making them reference parameters will merely reference what is passed. In this matter, C++ has the same semantics as C (in which you would use pointers for that).
1,294,417
1,294,460
Using LD to link intermediate files
If I have a.o, b.o, and c.o, how do I make ld link them into d.o, which is then linked into my main object file? All that I want to have happen is that all the symbols in the input files get combined into one big output file.
A concatenation of .o files is called a library. You create one with the ar library utility: ar rvs mylib.a a.o b.o c.o You can then link against the library: cc main.c mylib.a
1,294,465
1,298,481
Print server - want to catch print command
How should i know at print server whether any client has fire any command. or any way to hook into printer driver at printing driver at server What is print server ??? How print server work in Window??? How muliple client will send request to single print server??? Is any utility is running??? Can anybody clear me on this things???
It seems Microsoft do provide some APIs for intercepting the print spool: http://msdn.microsoft.com/en-us/library/ms802176.aspx Good luck!
1,294,756
1,294,826
Queue that uses a Stack
I am having trouble understanding a question. The question asks first to write a C++ class to represent a stack of integers, and that much is done. Here are my prototypes: class Stack{ private: int top; int item[100]; public: Stack() {top = -1;} ~Stack(); void push(int x) {item[++top] = x;} int pop() {return item[top--];} int empty(int top); }; The second part of the question says "Using the stack for storage purposes, write a C++ class to represent a queue of integers". My queue is as follows: class Queue{ private: int * data; int beginning, end, itemCount; public: Queue(int maxSize = 100); Queue(Queue &OtherQueue); ~Queue(); void enqueue(int x); void dequeue(); int amount(); }; I don't understand how I am meant to use a stack for storage purposes for a queue.
I don't agree with the existing answer. Typically, a queue is First In First Out, while a stack is obviously Last In First Out. I can only think of an implementation using two stacks, popping the whole thing and adding all but the last item to the second stack. Seems like a silly thing to do, but I guess it's for the sake of the exercise. As commented below, it is possible to do in amortized O(1), because the second stack will be in the right order. You can just take elements from the second stack, until you run out, in which case you move everything from the original stack to the second stack. A FIFO queue would just be a stack with Enqueue being Push and Dequeue being Pop. That doesn't make any sense as an exercise, so I'd definitely assume a FIFO queue was intended. Edit: added some links, something not easily done on my phone :)
1,294,805
1,308,893
Transparent window containing opaque text and buttons
I'm creating a non-intrusive popup window to notify the user when processing a time-consuming operation. At the moment I'm setting its transparency by calling SetLayeredWindowAttributes which gives me a reasonable result: alt text http://img6.imageshack.us/img6/3144/transparentn.jpg However I'd like the text and close button to appear opaque (it doesn't quite look right with white text) while keeping the background transparent - is there a way of doing this?
In order to do "proper" alpha in a layered window you need to supply the window manager with a PARGB bitmap by a call to UpdateLayeredWindow. The cleanest way to achieve this that I know of is the following: Create a GDI+ Bitmap object with the PixelFormat32bppPARGB pixel format. Create a Graphics object to draw in this Bitmap object. Do all your drawing into this object using GDI+. Destroy the Graphics object created in step 2. Call the GetHBITMAP method on the Bitmap object to get a Windows HBITMAP. Destroy the Bitmap object. Create a memory DC using CreateCompatibleDC and select the HBITMAP from step 5 into it. Call UpdateLayeredWindow using the memory DC as a source. Select previous bitmap and delete the memory DC. Destroy the HBITMAP created in step 5. This method should allow you to control the alpha channel of everything that is drawn: transparent for the background, opaque for the text and button. Also, since you are going to be outputting text, I recommend that you call SystemParametersInfo to get the default antialiasing setting (SPI_GETFONTSMOOTHING), and then the SetTextRenderingHint on the Graphics object to set the antialiasing type to the same type that is configured by the user, for a nicer look.
1,294,819
1,295,080
Can I convert the floating part of a double into an integer (without using string conversions)?
Example: If I have 7.2828, I just want to get the 2828 as an integer.
Decimal is your friend... Convert your number to a decimal and then do this. decimal d = (decimal)7.2828; int val = decimal.GetBits(d - decimal.Truncate(d))[0]; the neat thing about a decimal is that it stores the val as an int, and then just stores a decimal point position.
1,294,832
1,295,380
What is the correct way to instantiate an object with an allocator?
I have implemented a custom allocator (to be used by STL containers within my memory debugging utility, without them using my overridden new operator). Within the memory debugger I use an instance of the same allocator class to allocate the objects I need to keep track of 'normal' memory allocations. It's all working fine, but I'm not sure if the way I'm using the allocator interface is correct. Here are the utility methods as they currently stand (correct initialization parameters for the entry will be added soon): iidebug::CMemoryDebugger::CEntry* iidebug::CMemoryDebugger::NewEntry() { CEntry* pEntry = m_entryAllocator.allocate(1); if (0 != pEntry) { new(pEntry) CEntry(0, 0, __FILE__, 0, 0, 0); } return pEntry; } void iidebug::CMemoryDebugger::DeleteEntry( iidebug::CMemoryDebugger::CEntry* pEntry ) { if (0 != pEntry) { destruct(pEntry); m_entryAllocator.deallocate(pEntry, 1); } } This just seems very messy, but I can't see how I can improve it.
You can actually overload new and delete to take an allocator parameter, like so: inline void *operator new(size_t sizeT, Allocator *&a) { return a->allocate(sizeT); } inline void operator delete(void * mem, Allocator *&a) { a->release(mem); } int main() { Allocator * a = new Allocator; C *c = new(a) C; c->~C(); operator delete(c, a); return 0; } See the wikipedia article for more detail. It's still a bit messy because you have to be sure not to call the regular delete operator if your allocator does something special.
1,295,160
1,295,191
C++ IP Address human-readable form
In C/C++, you can use the regular gethostbyname() call to turn a dotted-IP address string ("127.0.0.1" in the case of localhost) into a structure suitable for standard socket calls. Now how do you translate it back? I know I can do some bit-shifting to get exactly which bit sets I want and just print those out, but is there any "standard" function to do this for me? It's for output into log files, so that I "really" know who/what I'm connecting to, and thus a human-readable dotted-address is a lot better than the raw hex. Thanks.
First of all, in new code you should generally prefer using getaddrinfo() to gethostbyname(), which is old and clunky and is tough to use to support both IPv4 and IPv6. See here: https://beej.us/guide/bgnet/html/multi/syscalls.html Secondly, the function that does what you want is called inet_ntop.
1,295,199
1,295,286
behavior of bool with non-boolean operators
What I really want is a ||= operator. old_value = old_value || possible_new_value; old_value ||= possible_new_value; The second line is a compiler error (c++ doesn't have a ||= operator). So what are my other options? old_value += possible_new_value; old_value |= possible_new_value; While I'm on the subject how does bool behave with other non-boolean operators? - -= & &= ... I can verify these empirically, but I'm most interested in what the standard says.
According to 4.7 (Integral conversions), paragraph 4, "If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one." In 4.12, "An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true." In a context where bool operands are not allowed but integral operands are, the bool will be converted to an integral type. When the integer result is stored in a bool variable, it will be converted to bool. Therefore, you will be able to use + and * as boolean or and and, and you can use | and & also. You can't get away with mixing them, as (bool1 + bool2) & bool3 will yield false if all three variables are true. ((1 + 1) & 1 is 2 & 1, which is 0, or false.) Remember that | and || don't work identically even here. | will evaluate both sides, and then evaluate the bitwise or. || will evaluate the first operand, then only if that was false will evaluate the second. I'm not going to discuss the stylistic issues here, but if I did anything like that I'd be sure to comment it so people knew what I was doing and why.
1,295,773
1,295,798
Header dependencies in qmake using MSVC Express
I'm using QtCreator on windows using MSVC compiler (the compiler from Visual c++ express edition) and qt 4.5.2 open source. When I modify a header on the project and press build all, nothing is actually built, only If I modify a .cpp file the modified cpp is compiled. That causes that every time that I have to change some header file used by several .cpp files I have to rebuild a complete project. There is a way to avoid this behavior? Thanks in advance
Are your header files listed in the HEADERS variable in your .pro file? I think listing header files in HEADERS is also required to get classes within them MOC'ed. **[edit]**Nevermind, I tested this out with Qt Creator 1.2.1 from the Qt 4.5.2 SDK on linux, and when I 'touch' a header file, the cpps it depends on are recompiled, whether or not the header is listed in the HEADER list. In the Makefile qmake generates, my cpp files that include the h file in question have a rule that explicitly lists the h file as a dependancy. Not sure how qmake does that. I'd suggest looking in the makefile qmake generated for you, and seeing what the rule for one of your cpp files looks like.[/edit] [edit again, getting off topic now]**Usually in make-based build system that invoke gcc, you generate dependency information for header files included by cpps by asking gcc to do it for you, with the -M flag. cl.exe (the microsoft C++ compiler) won't produce a .d file no matter how nicely you ask it, so it's somewhat common to use it's /showincludes option, and then parse the output with a script to convert it to a .d file so make can include it (a lot of people skip this step, and just don't have proper dependency checking in make-based builds that use cl.exe, because it's kind of a PITA). However, I don't think qmake does anything like that to get dependency information, because qmake is generating a makefile which in turn invokes the compiler, and at that point, the dependency info (at least in the makefile I looked at) is hard-coded.[/edit]**
1,296,185
1,324,032
Compile and optimize for different target architectures
Summary: I want to take advantage of compiler optimizations and processor instruction sets, but still have a portable application (running on different processors). Normally I could indeed compile 5 times and let the user choose the right one to run. My question is: how can I can automate this, so that the processor is detected at runtime and the right executable is executed without the user having to chose it? I have an application with a lot of low level math calculations. These calculations will typically run for a long time. I would like to take advantage of as much optimization as possible, preferably also of (not always supported) instruction sets. On the other hand I would like my application to be portable and easy to use (so I would not like to compile 5 different versions and let the user choose). Is there a possibility to compile 5 different versions of my code and run dynamically the most optimized version that's possible at execution time? With 5 different versions I mean with different instruction sets and different optimizations for processors. I don't care about the size of the application. At this moment I'm using gcc on Linux (my code is in C++), but I'm also interested in this for the Intel compiler and for the MinGW compiler for compilation to Windows. The executable doesn't have to be able to run on different OS'es, but ideally there would be something possible with automatically selecting 32 bit and 64 bit as well. Edit: Please give clear pointers how to do it, preferably with small code examples or links to explanations. From my point of view I need a super generic solution, which is applicable on any random C++ project I have later. Edit I assigned the bounty to ShuggyCoUk, he had a great number of pointers to look out for. I would have liked to split it between multiple answers but that is not possible. I'm not having this implemented yet, so the question is still 'open'! Please, still add and/or improve answers, even though there is no bounty to be given anymore. Thanks everybody!
If you wish this to cleanly work on Windows and take full advantage in 64bit capable platforms of the additional 1. Addressing space and 2. registers (likely of more use to you) you must have at a minimum a separate process for the 64bit ones. You can achieve this by having a separate executable with the relevant PE64 header. Simply using CreateProcess will launch this as the relevant bitness (unless the executable launched is in some redirected location there is no need to worry about WoW64 folder redirection Given this limitation on windows it is likely that simply 'chaining along' to the relevant executable will be the simplest option for all different options, as well as making testing an individual one simpler. It also means you 'main' executable is free to be totally separate depending on the target operating system (as detecting the cpu/OS capabilities is, by it's nature, very OS specific) and then do most of the rest of your code as shared objects/dlls. Also you can 'share' the same files for two different architectures if you currently do not feel that there is any point using the differing capabilities. I would suggest that the main executable is capable of being forced into making a specific choice so you can see what happens with 'lesser' versions on a more capable machine (or what errors come up if you try something different). Other possibilities given this model are: Statically linking to different versions of the standard runtimes (for ones with/without thread safety) and using them appropriately if you are running without any SMP/SMT capabilities. Detect if multiple cores are present and whether they are real or hyper threading (also whether the OS knows how the schedule effectively in those cases) checking the performance of things like the system timer/high performance timers and using code optimized to this behaviour, say if you do anything where you look for a certain amount of time to expire and thus can know your best possible granularity. If you wish to optimize you choice of code based on cache sizing/other load on the box. If you are using unrolled loops then more aggressive unrolling options may depend on having a certain amount level 1/2 cache. Compiling conditionally to use doubles/floats depending on the architecture. Less important on intel hardware but if you are targetting certain ARM cpu's some have actual floating point hardware support and others require emulation. The optimal code would change heavily, even to the extent you just use conditional compilation rather than using the optimizing compiler(1). Making use of co-processor hardware like CUDA capable graphics cards. detect virtualization and alter behaviour (perhaps trying to avoid file system writes) As to doing this check you have a few options, the most useful one on Intel being the the cpuid instruction. Windows Use someone else's implementation but you'll have to pay Use a free open source one Linux Use the built in one You could also look at open source software doing the same thing Pixman does a fair amount of this and is a permissive licence. Alternatively re-implement/update an existing one using available documentation on the features you need. Quite a lot of separate documents to work out how to detect things: Intel: SSE 4.1/4.2 SSE3 MMX A large part of what you would be paying for in the CPU-Z library is someone doing all this (and the nasty little issues involved) for you. be careful with this - it is hard to beat decent optimizing compilers on this
1,296,316
1,296,514
How to get the end of a C++ string stream?
I'm adding functions to my (simple) log class to make it usable like a stream. Currently, after some modifications, I got this (in my cpp): // blah blah blah... // note: here String is a defined as: typedef std::string String; void Log::logMessage( const String& message ) { logText(); // to be sure we flush the current text if any (when "composing" a message) addText( message ); logText(); // really log the message and make the current text empty } // blah blah blah... Log& operator<<( Log& log, const std::stringstream& message ) { log.logMessage( message.str() ); return log; } Log& operator<<( Log& log, const String& message ) { log.addText( message ); return log; } Now in my "client" app I'm using this code to check the result (m_log is a valid pointer as you have already guessed): gcore::Log& log = *m_log; log << getName() << " : application created."; log << "This is a test for " << getName(); Now the problem I got is that logText() (and logMessage) is never called because this test code will only call the << operator with String. What I need is a way to call logText() when the given steam of string is finished : log << getName() << " : application created."; would be equivalent to log.addText( getName() ); log.addText( " : application create." ); log.logText(); I'm not sure how to do this or even if it's possible. My first guess is that it would be possible to use std::endl at the end of the stream like this : log << getName() << " : application created." << std::endl; Or something equivalent, but if it's possible to do it without adding objects to the stream, that would be nice. Any idea?
You can create a temp object and use his destructor to catch the end of the statement: following code should give you the basic idea class Log { public: class Sublog { public: Sublog(const std::string& message) { std::cout << message; } void addText(const std::string& message) { std::cout << message; } ~Sublog() { std::cout << std::endl; } Sublog& operator<<(const std::string& message ) { this->addText(message); return *this; } }; }; Log::Sublog operator<<( Log& log, const std::string& message ) { return Log::Sublog(message); } which would be used like this int main() { Log log; log << "Foo" << "bar"; log << "baz" << "plop"; } after each semicolon, the destructor of Sublog is called Klaim: the (working and effective) implementation of this solution in my case : in the Log header : /** To allow streaming semantic on logs (used in << operator) . */ class LogStreamer { public: LogStreamer( Log& log, const String& text ) : m_log( log ) { m_log.addText( text ); } ~LogStreamer() { m_log.logText(); } LogStreamer& operator<<( const String& text ) { m_log.addText( text ); return *this; } private: Log& m_log; }; GCORE_API LogStreamer operator<<( Log& log, const String& message ); and in the cpp file: LogStreamer operator<<( Log& log, const String& message ) { return LogStreamer( log, message ); }
1,296,506
1,296,604
Getting a compile error : 0x2 trying to open file <vfdmsg>
I'm trying to build http://chitchat.at.infoseek.co.jp/vmware/vfd.html (VS 2008, Windows Server 2008 x64) however I'm getting the following error messages: Error 1 error : 0x2 trying to open file <vfdmsg>. mc lib Error 2 error PRJ0019: A tool returned an error code from "Compiling Message - L:\src\lib\vfdmsg.mc" lib lib Error 3 error : 0x2 trying to open file <vfdmsg>. mc cmd Error 4 error PRJ0019: A tool returned an error code from "Compiling Message - L:\src\cmd\vfdmsg.mc" cmd cmd Error 5 error : 0x2 trying to open file <vfdmsg>. mc gui Error 6 error PRJ0019: A tool returned an error code from "Compiling Message - L:\src\gui\vfdmsg.mc" gui gui I have the windows 2008 SDK installed and I've googled this for a while now but I cant for the life of me figure out what this error means. Can anyone help?
I've fixed this by noticing that the build step for vfdmsg.mc was: mc $(InputName) Where $(InputName) resolved to vfdmsg, not vfdmsg.mc Fixed by replacing this with the following build step: mc $(InputFileName)
1,296,674
1,296,757
How to implement scoped iostream formatting?
I'd like to scope-limit the effect of I/O stream formatting in C++, so that I can do something like this: std::cout << std::hex << ... if (some_condition) { scoped_iofmt localized(std::cout); std::cout << std::oct << ... } // outside the block, we're now back to hex so that base, precision, fill, etc. are restored to their previous values upon leaving the block. Here's the best I've come up with: #include <ios> class scoped_iofmt { std::ios& io_; // The true stream we shadow std::ios dummy_; // Dummy stream to hold format information public: explicit scoped_iofmt(std::ios& io) : io_(io), dummy_(0) { dummy_.copyfmt(io_); } ~scoped_iofmt() { try { io_.copyfmt(dummy_); } catch (...) {} } }; ... but c++ iostreams are a rather thorny area, and I'm not sure of the safety/appropriateness of the above. Is it dangerous? Have you (or has a third party) already done better?
Maybe something like the Boost I/O Stream State-saver library?
1,296,893
1,299,166
Boost best practices?
I've used Boost graph library a fair amount but not much of the rest of it. I frequently see recommendations here to use parts of Boost (say, Boost's various smart pointers). Obviously Boost is good and good to use. It is also large or diverse. Does anyone know of a FAQ or decent best practices doc to help a knowledgeable C++ programmer make better use of Boost?
I learned the libraries I use by other developers suggesting certain libraries and me reading all the documentation I could find/needed to use the library. However recently I bought this book, Beyond the C++ Standard, that introduces the most common parts of Boost. Even with reasonable boost experience I found this book really useful. It explains what the the libraries do, why they do it, how to use it and some of the techniques they use to implement it.
1,296,907
1,296,934
Function template specialization with reference to pointer
I have a template function: template<typename T> void foo(const T& value) { bar(value); x = -1; } I want to specialize it for a set of types: template<> void foo<char>(const char& value) { bar(value); x = 0; } template<> void foo<unsigned char>(const unsigned char& value) { bar(value); x = 1; } It works ok. When I compile this: template<> void foo<char*>(const char*& value) { bar(value); x = 2; } I get an error: error C2912: explicit specialization; 'void foo(const char *&)' is not a specialization of a function template Is it possible to specialize with char* pointer type parameter without typedef'ing it?
Sure. Try this: template<> void foo<char*>(char* const& value) {...} This is because const char* means pointer to const char, not a const pointer to char.
1,296,947
1,297,494
How to create binary/hex dump of another process's memory?
I am having trouble finding a reasonable way to dump another process's memory to a file. After extensive searching, I've been able to find a nice article at CodeProject that has *most* of the functionality I want: Performing a hex dump of another process's memory. This does a good job of addressing permission issues and sets a good foundation. However, with this utility I've seen that even a small process, such as an clean Notepad.exe or Calc.exe instance, can generate a dump file over 24MB in size, while the process itself runs under 20KB in memory according to TaskManager. The article has lead me to believe that perhaps it is also dumping things in shared memory, possibly DLL space and the like. For example, a dump of Calc.exe will include sections that include method names (and presumably memory) from Kernel32.dll: ²³´µKERNEL32.dll ActivateActCtx AddAtomA AddAtomW AddConsoleAliasA AddConsoleAliasW AddLocalAlternateComputerNameA AddLocalAlternateComputerNameW AddRefActCtx AddVectoredExceptionHandler AllocConsole AllocateUserPhysicalPages AreFileApisANSI AssignProcessToJobObject AttachConsole BackupRead BackupSeek BackupWrite BaseCheckAppcompatCache BaseCleanupAppcompatCache Is there a better way to dump the memory of another process that doesn't lead to this overhead, or perhaps an improvement upon the linked article's code that solves this problem? I want to get the memory that actually belongs to the process itself. I'd be okay with dumping the memory space of functions that are actually used in DLLs, but it seems unnecessary to dump the *entire* contents of multiple DLLs to get the running memory of the process. I'm looking for a way to get the 30-60KB of a 30KB process, rather than 25MB for a 30KB process. Or at least closer than I can get currently. Thanks in advance for your suggestions and guidance, it is appreciated. Note: This is for a console utility, so GUI elements like the ones in the CodeProject article are unimportant.
You're basically asking for a user process minidump. The Windows Debug Helper library has a ready made function for this, MiniDumpWriteDump. There is a coarse control over the amount of the detail contained in the mini dump from the MINIDUMP_TYPE parameter passed in to the function. The most basic, MiniDumpNormal, will only capture the call stack of each thread in the process. The amount of memory gets progressively more detailed with the other mini dump types. You can also fine control the amount of information to be written into the mini dump by providing a callback to the MiniDumpWriteDump function and in the callback set the flags on the MINIDUMP_CALLBACK_OUTPUT structure. The resulted mini dumps can be read with a debugger like Windbg or Visual Studio, or they can be processed by the various functions in the dbghelp.dll library.
1,297,059
1,297,106
C++: Callback typedefs with __stdcall in MSVC
This typedef: typedef DWORD WINAPI (* CM_Open_DevNode_Key)(DWORD, DWORD, DWORD, DWORD, PHKEY, DWORD); compiles fine in BorlandCpp, however, when I compile it in msvc I have to remove WINAPI (which is just an alias for __stdcall): typedef DWORD (* CM_Open_DevNode_Key)(DWORD, DWORD, DWORD, DWORD, PHKEY, DWORD); Why is this happening? Can I remove the WINAPI part safely? Update: I had to remove "WINAPI" form the typedef, otherwise I got error C2059: syntax error : '(' for the line. Can you tell me why Borland could compile it with "WINAPI" while Msvc couldn't?
I believe on VC++ you need to put the calling convention inside the ()'s Here's an example on MSDN of using a calling convention inside a function pointer typedef. typedef DWORD (WINAPI * CM_Open_DevNode_Key)(DWORD, DWORD, DWORD, DWORD, PHKEY, DWORD); This should compile without problem.
1,297,205
1,297,210
The C++ implicit this, and exactly how it is pushed on the stack
I need to know whether, when a class method in C++ is called, the implicit 'this' pointer is the first argument, or the last. i.e: whether it is pushed onto the stack first or last. In other words, I'm asking whether a class method, being called, is taken by the compiler to be: int foo::bar(foo *const this, int arg1, int arg2); //or: int foo::bar(int arg1, int arg2, foo *const this); By extension therefore, and more importantly, that would also answer whether G++ would push the this pointer last or first, respectively. I interrogated google, but I didn't find much. And as a side note, when C++ functions are called, do they do the same thing as C functions? i.e: push ebp mov ebp, esp All in all: would a class method being called look like this? ; About to call foo::bar. push dword 0xDEADBEEF push dword 0x2BADBABE push dword 0x2454ABCD ; This one is the this ptr for the example. ; this code example would match up if the this ptr is the first argument. call _ZN3foo3barEpjj Thanks, and much obliged. EDIT: to clarify things, I'm using GCC/G++ 4.3
This depends on the calling convention of your compiler and the target architecture. By default, Visual C++ will not push this on the stack. For x86, the compiler will default to "thiscall" calling convention and will pass this in the ecx register. If you specify __stdcall for you member function, it will be pushed on the stack as the first parameter. For x64 on VC++, the first four parameters are passed in registers. This is the first parameter and passed in the rcx register. Raymond Chen had a series some years ago on calling conventions. Here are the x86 and x64 articles.
1,297,609
1,297,635
Overloading friend operator << for template class
I'm trying to overload the operator << as a friend to a template class Pair, but I keep getting a compiler warning saying friend declaration std::ostream& operator<<(ostream& out, Pair<T,U>& v) declares a non template function for this code: friend ostream& operator<<(ostream&, Pair<T,U>&); it gives a second warning as a recommendation saying if this is not what you intended, make sure the function template has already been declared and add <> after the function name here Here is the function definition template <class T, class U> ostream& operator<<(ostream& out, Pair<T,U>& v) { out << v.val1 << " " << v.val2; } and here is the whole class. template <class T, class U> class Pair{ public: Pair(T v1, U v2) : val1(v1), val2(v2){} ~Pair(){} Pair& operator=(const Pair&); friend ostream& operator<<(ostream&, Pair<T,U>&); private: T val1; U val2; }; I wasn't sure what to draw from the recommendation warning, other than that maybe I have to put somewhere in the friend declaration. Does anyone know the proper syntax for this? Thanks.
You declare operator<< as returning an ostream&, but there is no return statement at all in the method. Should be: template <class T, class U> ostream& operator<<(ostream& out, Pair<T,U>& v) { return out << v.val1 << " " << v.val2; } Other than that, I have no problems or warnings compiling your code under Visual Studio 2008 with warnings at level 4. Oh, there are the classical linker errors, but that is easily bypassed by moving the template function definition to the class declaration, as explained in the C++ FAQ. My test code: #include <iostream> using namespace std; template <class T, class U> class Pair{ public: Pair(T v1, U v2) : val1(v1), val2(v2){} ~Pair(){} Pair& operator=(const Pair&); friend ostream& operator<<(ostream& out, Pair<T,U>& v) { return out << v.val1 << " " << v.val2; } private: T val1; U val2; }; int main() { Pair<int, int> a(3, 4); cout << a; }
1,297,688
1,297,708
A simple C++ question on memory usage
What is the difference (memory wise) bewteen: for(int x=0;x<100;x++) { int y = 1+x; } and int y = 0; for(int x=0;x<100;x++) { y = 1+x; } I've always wondered if they are the same or the first is a waste of memory?...
Memory-wise, there is no difference. y is on the stack, wherever it's declared within the method. Here the only difference is the scope of y: in the second case, it is restricted to the body of the for loop; in the first, it isn't. This is purely at the language-level: again, y is allocated in exactly the same way, that is, on the stack. Just to make this point perfectly clear, here's a code example: void method1() { for (;;) { int a = 10; } } void method2() { int a; for (;;) { a = 10; } } Here is the assembler generated in debug mode in both cases : # method1() 00000000 push ebp 00000001 mov ebp,esp 00000003 push eax 00000004 cmp dword ptr ds:[00662E14h],0 0000000b je 00000012 0000000d call 5D9FE081 00000012 xor edx,edx 00000014 mov dword ptr [ebp-4],edx 00000017 mov dword ptr [ebp-4],0Ah 0000001e nop 0000001f jmp 00000017 # method2() 00000000 push ebp 00000001 mov ebp,esp 00000003 push eax 00000004 cmp dword ptr ds:[002B2E14h],0 0000000b je 00000012 0000000d call 5ED1E089 00000012 xor edx,edx 00000014 mov dword ptr [ebp-4],edx 00000017 mov dword ptr [ebp-4],0Ah 0000001e nop 0000001f jmp 00000017 Even without knowing anything about assembly, you can see that both methods have exactly the same instructions. In other words, at the point where a is declared, nothing happens. There is an important difference however if you are using any type that has a constructor, say, an std::vector: at the point where it is declared, the constructor is called, so if you declare it within a loop, it will be reconstructed each time through the loop. For example: for (/* index */) { std::vector<int> a; // invokes the constructor of std::vector<int> everytime } // destructor called each time the object goes out of scope std::vector<int> a; // constructor only called once for (/* index */) { } The situation gets worse if you are using new: these two pieces of code behave very differently: for (/* index */) { char *a = new char[100]; // allocates 100 additional bytes every time ! } // must remember to delete[] a in the loop, otherwise it's a memory leak ! ////// char *a = new char[100]; // only one allocation for (/* index */) { }
1,297,710
1,299,806
boost.thread dead-lock and self-deletion
I am using boost::thread_group to create(using thread_group::create_thread()) and dispatch threads. In order to limit the max thread numbers, at the end of each thread, I remove the thread from the thread_group and delete the thread itself(so that I could decide whether new threads need to be created). However it hangs somewhere between the creation and deletion of the last thread (say the 999th one of 999 in total). My questions are: is it OK to delete the thread from within itself like what I do? if not, what the best way to achieve this why does my code hangs? Below are the related code: //1- code to create and dispatch thread { //mutex for map<thread_id, thread*> operations boost::mutex::scoped_lock lk(m_mutex_for_ptr); // create a thread for this->f(duplicate_hashes) boost::thread* p = m_thread_group.create_thread(boost::bind( &detectiveT<equal_predicate>::f, this, duplicate_hashes )); // save the <thread_id,thread pointer> map for later lookup & deletion m_thread_ptrs.insert(make_pair(p->get_id(), p)); // log to console for debug cout << "thread created: " << p->get_id() << ", " << m_thread_group.size() << ", " m_thread_ptrs.size() << "\n"; } //2- code of the thread execution void f(list<map_iterator_type>& l) { Do_something(l); boost::this_thread::at_thread_exit(boost::bind( &detectiveT<equal_predicate>::remove_this_thread, this )); } //3- code to delete the thread itself void remove_this_thread() { { //mutex for map<thread_id, thread*> operations boost::mutex::scoped_lock lk(m_mutex_for_ptr); boost::thread::id this_id(boost::this_thread::get_id()); map<boost::thread::id, boost::thread*>::iterator itr; itr = (m_thread_ptrs.find(this_id)); if(m_thread_ptrs.end() != itr) { // remove it from the control of thread_group m_thread_group.remove_thread(itr->second); // delete it delete itr->second; // remove from the map m_thread_ptrs.erase(this_id); // log to console for debug cout << "thread erased: " << this_id << ", " << m_thread_group.size() << ", " << m_thread_ptrs.size() << "\n"; } } }
Why don't you try to recycle the threads, since creation/destruction is expensive? Code a thread pool class and send tasks to it. The pool will either queue the tasks if it has no more available threads, create threads if current_threads < max_threads or just use what thread is available. Suggested implementation: Find out what your ideal thread count is. This is usually equal to the number of processors. Depending on how complicated you want this to be, you could create all the threads in the pool at once or add threads if current-thread-count < ideal-thread-count and all the existing threads are busy executing tasks. Assuming that you are creating all your threads at once, you need to pass a worker function to each of the threads to execute. This worker function will wait for tasks to become available and then execute them. Because the function either executes a task or waits for it, it won't return and the thread won't be destroyed. The thread pool can keep track of a task queue and manage a wait condition that indicates when there are tasks available in the queue. Each thread worker function waits on the wait condition and when there's a task available it wakes up and tries to do the task. You will have to do some synchronization; the easiest way would be to try and find an available thread pool implementation, like the one in Windows (Vista+ I think) or the one in QtConcurrent which would allow you to just pass the task, call run and let the OS/library worry about everything. Later edit: Check out http://threadpool.sourceforge.net/
1,297,935
1,496,020
Evaluate Expression in RAD Studio 2007's Watch
I know that most of you might have noticed now. When you try to evaluate an expression using watch on RAD Studio 2007, it does not evaluate. For example, if I had a vector, I could not do "vecData.size()", if I do "vecData.size", it just gives an address. Is there any other way to watch the size and view each element of the vector in RAD Studio while debugging?
If you disable the compiler optimisations in the project options, the debugger will then be able to evaluate vecData.size(). "Project Options->C++ Compiler->Optimizations->Disable all optimizations" set this option to "True". This works for 2009, I believe it is the same for 2007.
1,298,003
1,298,011
Calculate minimum area rectangle for a polygon
I have a need to calculate the minimum area rectangle (smallest possible rectangle) around the polygon. The only input i have is the number of points in polygon. I have the co-ordinates of the points also.
Use the rotating calipers algorithm for a convex polygon, or the convex hull otherwise. You will of course need the coordinates of the points in the polygon, not just the number of points.
1,298,316
1,327,241
Catching LoadLibrary() errors gracefully
I'm working on a piece of C++ software which runs on all Windows versions between Windows XP and Windows Vista. In my code, I developed a DLL which links against a standard library (the Qt library). Once my software is deployed, it's not unusual that the user doesn't have the exact same Qt build on his system but a slightly different configuration. There might be features disabled (so their Qt build doesn't export the same set of symbols) or the library might even be changed in ways which make the library binary incompatible to the original. At some point, I'm loading my DLL via a LoadLibrary() call. This pulls in whatever Qt library is on the user's system. If I'm lucky, their Qt build is compatible with what I used while developing my DLLs, so LoadLibrary() succeeds. However, depending on the changes they did to their Qt build, the LoadLibrary() call sometimes fails with "The specified Module could not be found."; this usually happens if their Qt build consists of less DLLs than my Qt build. So my DLL attempts to load e.g. QtFoo.dll but since this dll is not part of their Qt build, loading my DLL fails. "The specified Procedure could not be found."; this usually happens if they changes their Qt build so that certain features are disabled, which results in less exported symbols. My question is: how can I catch these errors gracefully? Right I'm simply using GetLastError() and then print either of the above two messages. However, it would be much more useful if I knew which module could not be found, or which procedure is missing. I noticed that when running an application in the explorer which links against a missing DLL, explorer manages to yield a nice 'The application foo could not be loaded since the required library blah.dll is missing'. Is there maybe some API available to get more information about why a LoadLibrary() call failed exactly?
Can MapAndLoad from ImageHLP.DLL may help. It returns a LOADED_IMAGE structure.
1,298,557
1,309,678
Yet another linker issue
I'm having a linking issue with a basic C++ program. No, I'm not including .cpp files! This is what's happening. main.cpp: #include "header.h" #include <iostream> int main() { std::cout << "Hello!"; } header.h: #ifndef _HEADER_H #define _HEADER_H class Something { public: printContents(); }; #endif something.cpp: #include "header.h" #include <iostream> Something::printContents() { cout << "This class's Contents!!"; } What's happening is that I get a compiler error going: multiple definitions of some standard C function, such as strtod: g++ -o ... main.o build/....main.o: In function `strtod': ../MinGW/bin/../lib/gcc/mingw32/3.4.5/../../../../include/stdlib.h:318: multiple definition of `strtod' build/..something.o:...something.cpp:(.text+0x0): first defined here collect2: ld returned 1 exit status If I get rid of #include <iostream> in one of the two occasions and get rid of the couts, it will compile. What's going on? I'm using g++ and NetBeans to compile. I tried in the command line: g++ *.h *.cpp -o program and the same thing happened.
The problem was in a multi-installation of MinGW. I had one already installed, and when I got Qt on my computer, it had installed it's own MinGW. Bummer, I ported the code to my university's servers and it ran OK. Bummer!! Thanks everybody for the help, I will definitely follow your guidelines in the future. Header names - no underscores Correct return type Real code in the forums! Leo Bruzzaniti
1,298,750
1,298,760
Access base class fn with same signature from derived class object
Is it possible to access a base class function which has the same signature as that of a derived class function using a derived class object?. here's a sample of what I'm stating below.. class base1 { public: void test() {cout<<"base1"<<endl;}; }; class der1 : public base1 { public: void test() {cout<<"der1"<<endl;}; }; int main() { der1 obj; obj.test(); // How can I access the base class 'test()' here?? return 0; }
You need to fully qualify the method name as it conflicts with the inherited one. Use obj.base1::test()
1,299,065
1,300,488
Deleting a pointer a different places results in different behaviors (crash or not)
This question is a refinement of this one, which went in a different direction than expected. In my multithreaded application, the main thread creates parameters and stores them: typedef struct { int parameter1; double parameter2; float* parameter3; } jobParams; typedef struct { int ID; void* params; } jobData; std::vector<jobData> jobs; // main thread for (int i = 0; i < nbJobs; ++i) { jobParams* p = new jobParams; // fill and store params jobData data; data.ID = i; data.params = p; jobs.push_back(data); } // start threads and wait for their execution // delete parameters for (int i = 0; i < jobs.size(); ++i) { delete jobs[i].params; } Then, each thread gets a pointer to a set of parameters, and calls a job function with it: // thread (generic for any job function and any type of params) jobData* job = main->getNextParams(); jobFunction(job->ID, job->params); The whole thing takes void* as argument to be able to use any structure for the parameters, but then the job function casts it back to the right struct: void* jobFunction(void* param) { jobParams* params = (jobParams*) param; // do stuff return 0; } My problem is the following: if I delete params at the end of jobFunction(), it works perfectly. However, I'd prefer to have the deletion taken care of by the threads or the main thread, such that I don't have to remember to delete the params for each jobFunction() that I write. If I try to delete params just after calling jobFunction() in the treads, or even in the main thread after being sure that all threads are done (and thus the params are not needed anymore), I get a heap corruption error: HEAP[prog]: Invalid Address specified to RtlFreeHeap( 02E90000, 03C2EE38 ) I'm using Visual Studio 2008 Pro, and I thus can't use valgrind or other *nix tools for debugging. All access to the main thread from the "child threads" are synchronized using a mutex, so the problem is not that I delete the same parameters twice. In fact, by using VS memory viewer, I know that the memory pointed by the jobParams pointer does not change between the end of jobFunction() and the point where I try to delete it (either in the main thread or in the "child threads"). I added the definition of both structures, as well as the way I'd like to delete the params.
Just as a thought .. can you try for (int i = 0; i < jobs.size(); ++i) { delete (jobParams*)jobs[i].params; } newing a type jobParams and then deleteing a void* might be the cause of your problems. Is there any reason you store params as a void* in jobData? I'd argue if you wish to have different types of jobParams then you should be using an inheritance hierarchy and not blindly casting to a void*.
1,299,104
1,299,121
basic pointer question in c++ program
I looking for a clarification regarding the pointers. I have compiled the following code in bordland c++ 5.5.1 without any errors. But while i am trying to execute gives a core error. int main () { int x=10,y=20; int &a=x; int &b=y; int *c; int *d; *c=x; *d=y; return 0; } Basically I am trying to create two reference variable (a,b) and assigned with two variables (x,y). after that I created two pointer variable(c,d) and tried to assign same variables (x,y). This gives me error while exection and not at compilation. whether I am doing any wrong, this is not a standard assignments of pointer variable. why the pointer assignment is getting failed at this point. Please help me to understand this. 1st Update: Thanks to all. First, I understood that I am working on a C++ feature (reference variable). Second, I need to allocate memory for the pointer variables before play with it.
The code you posted is C++, not C. And your problem is that you need to make those pointers actually point at something: int * c = & x; // make c point at x * c = 42; // changes x
1,299,272
1,299,747
Difference between code generated using a template function and a normal function
I have a vector containing large number of elements. Now I want to write a small function which counts the number of even or odd elements in the vector. Since performance is a major concern I don't want to put an if statement inside the loop. So I wrote two small functions like: long long countOdd(const std::vector<int>& v) { long long count = 0; const int size = v.size(); for(int i = 0; i < size; ++i) { if(v[i] & 1) { ++count; } } return count; } long long countEven(const std::vector<int>& v) { long long count = 0; const int size = v.size(); for(int i = 0; i < size; ++i) { if(0 == (v[i] & 1)) { ++count; } } return count; } My question is can I get the same result by writing a single template function like this: template <bool countEven> long long countTemplate(const std::vector<int>& v1) { long long count = 0; const int size = v1.size(); for(int i = 0; i < size; ++i) { if(countEven) { if(v1[i] & 1) { ++count; } } else if(0 == (v1[i] & 1)) { ++count; } } return count; } And using it like this: int main() { if(somecondition) { countTemplate<true>(vec); //Count even } else { countTemplate<false>(vec); //Count odd } } Will the code generated for the template and non-template version be the same ? or will there be some additional instructions emitted? Note that the counting of numbers is just for illustration hence please don't suggest other methods for counting. EDIT: Ok. I agree that it may not make much sense from performance point of view. But atleast from maintainability point of view I would like to have only one function to maintain instead of two.
Your template version will generate code like this: template <> long long countTemplate<true>(const std::vector<int>& v1) { long long count = 0; const int size = v1.size(); for(int i = 0; i < size; ++i) { if(true) { if(v1[i] & 1) { ++count; } } else if(0 == (v1[i] & 1)) { ++count; } } return count; } template <> long long countTemplate<false>(const std::vector<int>& v1) { long long count = 0; const int size = v1.size(); for(int i = 0; i < size; ++i) { if(false) { if(v1[i] & 1) { ++count; } } else if(0 == (v1[i] & 1)) { ++count; } } return count; } So if all optimizations are disabled, the if will in theory still be there. But even a very naive compiler will determine that you're testing a constant, and simply remove the if. So in practice, no, there should be no difference in the generated code. So you can use the template version and don't worry about this.
1,299,422
1,299,449
How do I port code that contains #pragma optimize( "a" ) from VC++7 to VC++9?
I'm moving my C++ codebase from Visual Studio 2k3 to Visual Studio 2k8. Code contains #pragma optimize( "a", on ) MSDN says that it means "assume no aliasing". Later versions of VS refuse to compile this and MSDN doesn't seem to say what to do with code containing this #pragma. What does "assume no aliasing" mean and how to I make a decision on what to do with this line of code?
Aliasing is when you have stuff like this: int a[100]; int * p1 = &a[50]; int * p2 = &a[52]; Now a, p1 and p2 are all aliases for the array, or parts of it. This situation can prevent the compiler from producing optimal array access code (FORTRAN forbids it, which is why it is so good with array performance). The pragma you are asking about says that the compiler can assume the above situation doesn't exist. Obviously, if you need to decide whether you need this you can do one of two things: check all your code (difficult and error prone) turn it off and see if there is any performance degradations (easy and sensible) The choice is yours :-)
1,299,691
1,299,810
When does the C++ default assignment operator become unaccessible?
If I define an own assignment operator, which has a different signature than the normally generated default assignment operator: struct B; struct A { void operator = (const B& b) { // assign something } }; does the default assignment operator, in this case operator = (A&) (or the like, correct me if wrong) become undefined/unaccessible? AFAIK this is true for the default constructor, which doesn't exist, if we define some other constructor. But I am really not sure if this is the case for the other "magic" defaults. The reason I ask: I want to avoid that the default copy constructor is accidently called via a implicit type conversion. If it doesn't exist, it could never happen.
No. 12.8/9 says that the assignment operator for class X must be non-static, non-template with a parameter of type X, X&, X const&, X volatile& or X const volatile&. And there is a note which emphasizes that the instantiation of a template doesn't suppress the implicit declaration.
1,300,122
1,302,300
Marshalling BSTRs from C++ to C# with COM interop
I have an out-of-process COM server written in C++, which is called by some C# client code. A method on one of the server's interfaces returns a large BSTR to the client, and I suspect that this is causing a memory leak. The code works, but I am looking for help with marshalling-out BSTRs. Simplifying a bit, the IDL for the server method is HRESULT ProcessRequest([in] BSTR request, [out] BSTR* pResponse); and the implementation looks like: HRESULT MyClass::ProcessRequest(BSTR request, BSTR* pResponse) { USES_CONVERSION; char* pszRequest = OLE2A(request); char* pszResponse = BuildResponse(pszRequest); delete pszRequest; *pResponse = A2BSTR(pszResponse); delete pszResponse; return S_OK; } A2BSTR internally allocates the BSTR using SysAllocStringLen(). In the C# client I simply do the following: string request = "something"; string response = ""; myserver.ProcessRequest(request, out response); DoSomething(response); This works, in that request strings get sent to the COM server and correct response strings are returned to the C# client. But every round trip to the server leaks memory in the server process. The crt leak detection support is showing no significant leaks on the crt heap, so I'm suspecting the leak was allocated with IMalloc. Am I doing anything wrong here? I have found vague comments that 'all out parameters must be allocated with CoTaskMemAlloc, otherwise the interop marshaller won't free them' but no details. Andy
anelson has covered this pretty well, but I wanted to add a couple of points; CoTaskMemAlloc is not the only COM-friendly allocator -- BSTRs are recognized by the default marshaller, and will be freed/re-allocated using SysAllocString & friends. Avoiding USES_CONVERSION (due to stack overflow risks -- see anelson's answer), your full code should be something like this [1] (note that A2BSTR is safe to use, as it calls SysAllocString after conversion, and doesn't use dynamic stack allocation. Also, use array-delete (delete[]) as BuildResponse likely allocates an array of chars) The BSTR allocator has a cache that can make it appear as though there is a memory leak. See http://support.microsoft.com/kb/139071 for some details, or Google for OANOCACHE. You could try disabling the cache and see if the 'leak' goes away. [1] HRESULT MyClass::ProcessRequest(BSTR request, BSTR* pResponse) { char* pszResponse = BuildResponse(CW2A(request)); *pResponse = A2BSTR(pszResponse); delete[] pszResponse; return S_OK; }
1,300,180
1,300,240
Ignore OpenMP on machine that does not have it
I have a C++ program using OpenMP, which will run on several machines that may have or not have OpenMP installed. How could I make my program know if a machine has no OpenMP and ignore those #include <omp.h>, OpenMP directives (like #pragma omp parallel ...) and/or library functions (like tid = omp_get_thread_num();) ?
OpenMP is a compiler runtime thing and not a platform thing. ie. If you compile your app using Visual Studio 2005 or higher, then you always have OpenMP available as the runtime supports it. (and if the end-user doesn't have the Visual Studio C runtime installed, then your app won't work at all). So, you don't need to worry, if you can use it, it will always be there just like functions such as strcmp. To make sure they have the CRT, then you can install the visual studio redistributable. edit: ok, but GCC 4.1 will not be able to compile your openMP app, so the issue is not the target machine, but the target compiler. As all compilers have pre-defined macros giving their version, wrap your OpenMP calls with #ifdef blocks. for example, GCC uses 3 macros to identify the compiler version, __GNUC__, __GNUC_MINOR__ and __GNUC_PATCHLEVEL__
1,300,327
1,300,346
Sort function does not work with function object created on stack?
#include<iostream> #include<vector> #include<algorithm> class Integer { public: int m; Integer(int a):m(a){}; }; class CompareParts { public: bool operator()(const Integer & p1,const Integer & p2) { return p1.m<p2.m; } }obj1; int main() { std::vector<Integer> vecInteger; vecInteger.push_back(Integer(12)); vecInteger.push_back(Integer(13)); vecInteger.push_back(Integer(5)); vecInteger.push_back(Integer(7)); vecInteger.push_back(Integer(9)); Integer obj2(); std::sort(vecInteger.begin(),vecInteger.end(),obj1); std::sort(vecInteger.begin(),vecInteger.end(),obj2); } why is obj2 in second sort function leads to compiler error.
Integer obj2() isn't the definition of an object, it is the declaration of a function named obj2 returning an Integer (put it outside any function to understand why it is so). This occurs also sometimes with more complex constructions where it can be even more confusing. Some name this the most vexing parse. Here is the promised example of a more complex case: struct Foo {}; struct Bar { Bar(Foo); }; Bar quxx(Foo()); // quxx is a function Here quxx is a function returning a Bar and taking (a pointer) to a function returning a Foo and without parameters. You could write the same declaration more clearly like this: Bar quxx(Foo (*fn)()); // quxx is the same function as above To get the definition of a variable initialized with the constructor taking a Foo, you can add a level of parenthesis: Bar quux((Foo())); // quux is a variable
1,300,565
1,300,991
How should I compare a c++ metaprogram with an C code ? (runtime )
I have ported a C program to a C++ Template Meta program .Now i want to compare the runtime . Since there is almost no runtime in the C++ program , how should i compare these 2 programs. Can i compare C runtime with C++ compile time ? or is it just not comparable ?
You can compare anything you want to compare. There is no one true rule of what should be compared. You can compare the time each version takes to execute, or you can compare the time taken to compile each. Or you can compare the length of the program, or the number of 'r' characters in the source file. You could compare the timestamp of each file. How you should compare the two programs depend on what you want to show! If you want to show that one executes faster than the other, then run both, time how long they take to execute, and compare those numbers. If you want to show that one compiles faster than the other, then time the time it takes to compile them. If you think the relation between the compile time of the C++ program and the run time of the C program is relevant, then compare those. Decide what it is you want to show. Then you'll know what to compare.
1,300,623
2,342,681
Can someone provide an example of seeking, reading, and writing a >4GB file using boost iostreams
I have read that boost iostreams supposedly supports 64 bit access to large files semi-portable way. Their FAQ mentions 64 bit offset functions, but there is no examples on how to use them. Has anyone used this library for handling large files? A simple example of opening two files, seeking to their middles, and copying one to the other would be very helpful. Thanks.
Short answer Just include #include <boost/iostreams/seek.hpp> and use the seek function as in boost::iostreams::seek(device, offset, whence); where device is a file, stream, streambuf or any object convertible to seekable; offset is a 64-bit offset of type stream_offset; whence is BOOST_IOS::beg, BOOST_IOS::cur or BOOST_IOS::end. The return value of seek is of type std::streampos, and it can be converted to a stream_offset using the position_to_offset function. Example Here is an long, tedious and repetitive example, which shows how to open two files, seek to offstets >4GB, and copying data between them. WARNING: This code will create very large files (several GB). Try this example on an OS/file system which supports sparse files. Linux is ok; I did not test it on other systems, such as Windows. /* * WARNING: This creates very large files (several GB) * unless your OS/file system supports sparse files. */ #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/positioning.hpp> #include <cstring> #include <iostream> using boost::iostreams::file_sink; using boost::iostreams::file_source; using boost::iostreams::position_to_offset; using boost::iostreams::seek; using boost::iostreams::stream_offset; static const stream_offset GB = 1000*1000*1000; void setup() { file_sink out("file1", BOOST_IOS::binary); const char *greetings[] = {"Hello", "Boost", "World"}; for (int i = 0; i < 3; i++) { out.write(greetings[i], 5); seek(out, 7*GB, BOOST_IOS::cur); } } void copy_file1_to_file2() { file_source in("file1", BOOST_IOS::binary); file_sink out("file2", BOOST_IOS::binary); stream_offset off; off = position_to_offset(seek(in, -5, BOOST_IOS::end)); std::cout << "in: seek " << off << std::endl; for (int i = 0; i < 3; i++) { char buf[6]; std::memset(buf, '\0', sizeof buf); std::streamsize nr = in.read(buf, 5); std::streamsize nw = out.write(buf, 5); std::cout << "read: \"" << buf << "\"(" << nr << "), " << "written: (" << nw << ")" << std::endl; off = position_to_offset(seek(in, -(7*GB + 10), BOOST_IOS::cur)); std::cout << "in: seek " << off << std::endl; off = position_to_offset(seek(out, 7*GB, BOOST_IOS::cur)); std::cout << "out: seek " << off << std::endl; } } int main() { setup(); copy_file1_to_file2(); }
1,300,718
1,300,903
C++ .NET convert System::String to std::string
How do you convert System::String to std::string in C++ .NET?
There is cleaner syntax if you're using a recent version of .net #include "stdafx.h" #include <string> #include <msclr\marshal_cppstd.h> using namespace System; int main(array<System::String ^> ^args) { System::String^ managedString = "test"; msclr::interop::marshal_context context; std::string standardString = context.marshal_as<std::string>(managedString); return 0; } This also gives you better clean-up in the face of exceptions. There is an msdn article for various other conversions
1,300,769
1,300,798
Threads in C, C++, C++0x, pthread and boost
A question about threads in C/C++... C++0x syntax #include <thread> void dummy() {} int main(int, char*[]) { std::thread x(dummy); std::thread y(dummy); ... return 0; } How many threads are there? Two (x and y) or three (x, y and main)? Can I call this_thread::yield() in main? And what do I get from calling this_thread::get_id() in main? pthread syntax #include <pthread.h> void dummy() {} int main(int, char*[]) { pthread_t x, y; pthread_create(&x, NULL, &dummy, NULL); pthread_create(&y, NULL, &dummy, NULL); ... return 0; } How many threads are there? Two (x and y) or three (x, y and main)? Can I call pthread_yield() in main? And what do I get from calling pthread_self() in main? boost syntax #include <boost/thread> void dummy() {} int main(int, char*[]) { boost::thread x(dummy); boost::thread y(dummy); ... return 0; } How many threads are there? Two (x and y) or three (x, y and main)? Can I call boost::this_thread::yield() in main? And what do I get from calling boost::this_thread::get_id() in main?
In each case you have created two additional threads so you have three (x, y, and main). You'll get a different id on each of the threads including a call in main.
1,300,778
1,300,820
How to prevent the linker from optimizing away startup code?
I have the following problem: My (C++-)project consists of several subprojects. In each, I have several files with code I want to run at startup. My solution so far is to use static variables which call the respective code on initialization like this: // Foo.cpp static TFooRegistry sFooRegistry; // does stuff in constructor. When building my project using dlls for each subproject, everything works fine and the code runs as expected. When linking the subprojects statically, however, the linker determines that Foo.o contains no code ever referenced from outside and optimizes it away. Of course I could add a reference to sFooRegistry somewhere else, but this is tedious and error prone. What (standard conformant) ways of solving this are there? OK, what can I do on mac/gcc and win/visual studio?
There are no standard conformant ways of forcing objects in libraries to be initialised - you have to use tricks depending on your particular platform(s). The difference between a DLL and and a static library (on Windows, at least) is that the former has start-up and shut-down code that is executed by the OS, whereas the latter is just a concatenation of object files. Also, the linker is not optimising away your start up code - it is simply not linking it, because it apparently is never used. Linkers are pretty stupid beasts - if you want to find out how they do what they do, take a look at the book Linkers & Loaders.
1,301,051
1,301,061
Map pointers to immutable objects with Hashtable in .NET
I have a Hashtable object which "names" or "map" various fields in a class with a string ref class Interrupt{ Interrupt(){ this->type = 0; this->size = 0; } int type; int size; } Interrupt^ interrupt = gcnew Interrupt(); Hashtable^ map = gcnew Hashtable(); map->Add("InterruptType", interrupt->type); map->Add("InterruptSize", interrupt->size); this class is modified during runtime so type and size are both equals to 2. further down the road I query my Hashtable but the values didn't change. I understand that it is because they are immutable. Is there a way I can specify my Hashtable to hold pointers to the fields of my class instead of storing the value of the reference? I know I can modify class Interrupt to hold custom objects instead of raw int, but it would invole A LOT of refactoring.
I understand that it is because they are immutable. You understand wrong. Yes, integers are immutable. But the map values didn't change because integers are value types, and so were passed to the map's Add() method by value. In other words, the map holds a copy of the value passed to the Add() method rather than a reference to the variable passed to the method. To fix this, you need to wrap your integers in a reference type (a class) and give the map a reference to the desired instance of that class. Then make sure that whenever you change your integers you're changing them as members of the correct instance.
1,301,056
1,301,202
Looking for the most elegant code dispatcher
I think the problem is pretty common. You have some input string, and have to call a function depending on the content of the string. Something like a switch() for strings. Think of command line options. Currently I am using: using std::string; void Myclass::dispatch(string cmd, string args) { if (cmd == "foo") cmd_foo(args); else if (cmd == "bar") cmd_bar(args); else if ... ... else cmd_default(args); } void Myclass::cmd_foo(string args) { ... } void Myclass::cmd_bar(string args) { ... } and in the header class Myclass { void cmd_bar(string args); void cmd_foo(string args); } So every foo and bar I have to repeat four (4!) times. I know I can feed the function pointers and strings to an static array before and do the dispatching in a loop, saving some if...else lines. But is there some macro trickery (or preprocessor abuse, depending on the POV), which makes is possible to somehow define the function and at the same time have it update the array automagically? So I would have to write it only twice, or possibly once if used inline? I am looking for a solution in C or C++.
The ugly macro solution, which you kind-of asked for. Note that it doesn't automatically register, but it does keep some things synchronized, and also will cause compile errors if you only add to mappings, and not the function in the source file. Mappings.h: // Note: no fileguard // The first is the text string of the command, // the second is the function to be called, // the third is the description. UGLY_SUCKER( "foo", cmd_foo, "Utilize foo." ); UGLY_SUCKER( "bar", cmd_bar, "Turn on bar." ); Parser.h: class Myclass { ... protected: // The command functions #define UGLY_SUCKER( a, b, c ) void b( args ) #include Mappings.h #undef UGLY_SUCKER }; Parser.cpp: void Myclass::dispatch(string cmd, string args) { if (cmd == "") // handle empty case #define UGLY_SUCKER( a, b, c ) else if (cmd == a) b( args ) #include Mappings.h #undef UGLY_SUCKER else cmd_default(args); } void Myclass::printOptions() { #define UGLY_SUCKER( a, b, c ) std::cout << a << \t << c << std::endl #include Mappings.h #undef UGLY_SUCKER } void Myclass::cmd_foo(string args) { ... }
1,301,099
1,301,123
VC++ LNK2001: unresolved external symbol only when compiling on 64bit
I have made a dll that compiles fine in 32bit mode, but when compiling in 64bit mode (both on a 32bit box cross compiling and on a native 64bit box) I get the above error. The symbol that it is complaining about are the following: "struct return_info_ * __cdecl patch_file(char *,char *,char *)" I am new to C++ but I think I have defined both the struct and the signature correctly. The struct "return_info_" is defined as follows: typedef struct return_info_ { char *message; int code; } return_info; In the same header I have the signature of the function: return_info* patch_file(char* oldfile, char* newfile, char* patchfile); This is all in native c/c++ code, which is compiled as a statically linked library. I then have our main library which links to this and is a clr compatible binary. Any ideas why the 64bit compiler throws these errors?
The declaration in the header looks correct, but for some reason, in your 64bit build, the actual implementation not being found. Is this defined in your library? It may not have been compiled correctly in its 64bit version. If this is a function that's part of your application, make sure the correct source file is being included as part of the 64bit build process, as well.
1,301,277
1,301,343
C++ Boost: what's the cause of this warning?
I have a simple C++ with Boost like this: #include <boost/algorithm/string.hpp> int main() { std::string latlonStr = "hello,ergr()()rg(rg)"; boost::find_format_all(latlonStr,boost::token_finder(boost::is_any_of("(,)")),boost::const_formatter(" ")); This works fine; it replaces every occurrence of ( ) , with a " " However, I get this warning when compiling: I'm using MSVC 2008, Boost 1.37.0. 1>Compiling... 1>mainTest.cpp 1>c:\work\minescout-feat-000\extlib\boost\algorithm\string\detail\classification.hpp(102) : warning C4996: 'std::copy': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators' 1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\xutility(2576) : see declaration of 'std::copy' 1> c:\work\minescout-feat-000\extlib\boost\algorithm\string\classification.hpp(206) : see reference to function template instantiation 'boost::algorithm::detail::is_any_ofF<CharT>::is_any_ofF<boost::iterator_range<IteratorT>>(const RangeT &)' being compiled 1> with 1> [ 1> CharT=char, 1> IteratorT=const char *, 1> RangeT=boost::iterator_range<const char *> 1> ] 1> c:\work\minescout-feat-000\minescouttest\maintest.cpp(257) : see reference to function template instantiation 'boost::algorithm::detail::is_any_ofF<CharT> boost::algorithm::is_any_of<const char[4]>(RangeT (&))' being compiled 1> with 1> [ 1> CharT=char, 1> RangeT=const char [4] 1> ] I could certainly disable the warning using -D_SCL_SECURE_NO_WARNINGS but I'm a bit reluctant to do that before I find out what's wrong, or more importantly if my code is incorrect.
It is nothing to worry about. In the last few releases of MSVC, they've gone into full security-paranoia mode. std::copy issues this warning when it is used with raw pointers, because when used incorrectly, it can result in buffer overflows. Their iterator implementation performs bounds checking to ensure this doesn't happen, at a significant performance cost. So feel free to ignore the warning. It doesn't mean there's anything wrong with your code. It is just saying that if there is something wrong with your code, then bad things will happen. Which is an odd thing to issue warnings about. ;)
1,301,380
1,301,465
g++ "is not a type" error
Writing a templated function, I declared: template <typename T> T invertible(T const& container, T::size_type startIndex, T::size_type endIndex); Compiling with g++ 4.0.1 I got the error: error: 'T::size_type' is not a type
As you found out T::size_type needs to be prefixed with typename. Why? From "C++ Templates: The Complete Guide" The language definition resolves this problem by specifying that in general a dependent qualified name does not denote a type unless that name is prefixed with the keyword typename. ... The typename prefix to a name is required when the name Appears in a template Is qualified Is not used as a list of base class specifications or in a list of member initializations introducing a constructor definition Is dependent on a template parameter Furthermore the typename prefix is not allowed unless at least the first three previous conditions hold.
1,301,543
1,301,579
Unresolved External (abstract class constructor/destructor)
So, I have an abstract class Panel and an implementation of it MyPanel. They look similar to this: class Panel : public QWidget { public: Panel(QWidget* parent = 0) = 0; virtual ~Panel() = 0; // but wait, there's more!! }; class MyPanel : public Panel { public: MyPanel(QWidget* parent = 0); ~MyPanel() {}; // nothing to do here }; MyPanel::MyPanel(QWidget* parent) : Panel(parent) { // you must construct additional pylons } I'm getting linker errors for the constructor/destructor from VC++ error LNK2019: unresolved external symbol "public: virtual __thiscall Panel::~Panel(void)" (??1Panel@@UAE@XZ) referenced in function "public: virtual __thiscall MyPanel::~MyPanel(void)" (??1MyPanel@@UAE@XZ) mypanel.obj error LNK2019: unresolved external symbol "public: __thiscall Panel::Panel(class QWidget *)" (??0Panel@@QAE@PAVQWidget@@@Z) referenced in function "public: __thiscall MyPanel::MyPanel(class QWidget *)" (??0MyPanel@@QAE@PAVQWidget@@@Z) mypanel.obj Why am I getting this linker error? --- THE ANSWER --- class Panel : public QWidget { public: Panel(QWidget* parent = 0) : QWidget(parent) {}; virtual ~Panel() {}; // but wait, there's more!! }; I thought I had tried this before lunch. Turns out I was wrong.
there is no such thing like virtual constructor. You still should provide implementation of destructor.
1,301,736
1,301,785
Can you rewrite this snippet without goto
Guys, I have the following code that is inside a big while loop that iterates over a tree. This is as fast as I can get this routine but I have to use a goto. I am not fundamentally against goto but if I can avoid them I would like to. (I am not trying to start a flame war, please.) The constraints: The current=current->child() is expensive (it's a shared_ptr) so I'd like to minimize the use of that operation at all cost. After the operation current should be the last child it found. cnt must count each child it encounters. cnt++ will be replaced by some other operation (or several operations) and should only appear once :) the code: insideloopy: cnt++; if ( current->hasChild() ) { current = current->child(); goto insideloopy; } Edit: Sorry guys, originally forgot to mention cnt++ should only appear once. It will be some kind of operation on the node, and should thus only be there one time. I'm also trying to avoid making that another function call.
insideloopy: cnt++; if ( current->hasChild() ) { current = current->child(); goto insideloopy; } I love infinite loops. while (true) { cnt++; if (!current->hasChild()) break; current = current->child(); } Of course you can do it in many other ways (see other answers). do while, put the check in the while, etc. In my solution, I wanted to map nearly to what you are doing (an infinite goto, unless break)
1,301,850
1,304,994
Tools to find included headers which are unused?
I know PC-Lint can tell you about headers which are included but not used. Are there any other tools that can do this, preferably on linux? We have a large codebase that through the last 15 years has seen plenty of functionality move around, but rarely do the leftover #include directives get removed when functionality moves from one implementation file to another, leaving us with a pretty good mess by this point. I can obviously do the painstaking thing of removing all the #include directives and letting the compiler tell me which ones to reinclude, but I'd rather solve the problem in reverse - find the unused ones - rather than rebuilding a list of used ones.
DISCLAIMER: My day job is working for a company that develops static analysis tools. I would be surprised if most (if not all) static analysis tools did not have some form of header usage check. You could use this wikipedia page to get a list of available tools and then email the companies to ask them. Some points you might consider when you're evaluating a tool: For function overloads, you want all headers containing overloads to be visible, not just the header that contains the function that was selected by overload resolution: // f1.h void foo (char); // f2.h void foo (int); // bar.cc #include "f1.h" #include "f2.h" int main () { foo (0); // Calls 'foo(int)' but all functions were in overload set } If you take the brute force approach, first remove all headers and then re-add them until it compiles, if 'f1.h' is added first then the code will compile but the semantics of the program have been changed. A similar rule applies when you have partial and specializations. It doesn't matter if the specialization is selected or not, you need to make sure that all specializations are visible: // f1.h template <typename T> void foo (T); // f2.h template <> void foo (int); // bar.cc #include "f1.h" #include "f2.h" int main () { foo (0); // Calls specialization 'foo<int>(int)' } As for the overload example, the brute force approach may result in a program which still compiles but has different behaviour. Another related type of analysis that you can look out for is checking if types can be forward declared. Consider the following: // A.h class A { }; // foo.h #include "A.h" void foo (A const &); // bar.cc #include "foo.h" void bar (A const & a) { foo (a); } In the above example, the definition of 'A' is not required, and so the header file 'foo.h' can be changed so that it has a forward declaration only for 'A': // foo.h class A; void foo (A const &); This kind of check also reduces header dependencies.
1,301,923
1,301,954
Reading binary files without buffering the whole file into memory in C++
In order to make a binary comparer I'm trying to read in the binary contents of two files using the CreateFileW function. However, that causes the whole file to be bufferred into memory, and that becomes a problem for large (500MB) files. I've looked around for other functions that'll let me just buffer part of the file instead, but I haven't found any documentation specifically stating how the buffer works for those functions (I'm a bit new at this so maybe I'm missing the obvious). So far the best match I seem to have found is ReadFile. It seems to have a definable buffer but I'm not completely sure that there won't be another buffer implemented behind the scenes, like there is with CreateFileW. Do you guys have any input on what would be a good function to use?
You could use memory mapped files to do this. open with createFile, use createFileMapping then MapViewOfFile to get a pointer to the data.
1,302,025
1,302,294
Game engine map editor. SDL->wxWidgets
I have been writing an OpenGL game engine for a while which uses SDL for all the window management and for portability. I would like to create a level editor using the full engine. The engine itself isn't at all tied in with SDL except for input. I would like to use wxWidgets for the GUI and I have been looking at some OpenGL samples which are quite simple and easy to understand. Would it be simpler to try and integrate SDL with wxWidgets and use both or switch between them for use in different applications? What would be the best way to switch between the two systems?
In all likelihood it would be easier to use one GUI API per application as opposed to merging the two together (i.e. easier to have SDL/OpenGL in your game and wxWidgets/OpenGL in your level editor). Usually these libraries are not built to be merged together or used in conjunction with other libraries so it would be nearly impossible to use them both in one program. For example, I don't know much about SDL, but a correctly-written wxWidgets program uses internal macros to generate int main() and start up its message pump, among other things. If SDL required you to do the same thing (run some special initialization code in your int main() or allow SDL to generate its own int main()) you would be unable to initialize SDL properly without breaking wxWidgets, and vice versa. Again, I don't know if this particular conflict actually exists between the two libraries, but it's just an example of how the two can interact and interfere with each other. That said, in a perfect world it would be better to choose one of the libraries and use it both for your engine and level editor (i.e. use SDL/OpenGL for the engine and editor, or wxWidgets/OpenGL for the engine and editor), but if you're happy maintaining two different API codebases, then if it ain't broke, don't fix it.
1,302,141
1,365,223
How do I create and maintain a code reuse library?
I am trying to setup a repository of reusable code. I was thinking about having each reusable code module have a certain “Maturity Level” rating. The rating would be defined as the level at which a reusable code lies within a certain set of requirements. The highest maturity level will be the highest degree of standard across a predefined set of requirements. For example: Level; Requirements; Description Level 0; Code is legal to use; Is the code legal to use in commercial industry/across multiple contracts/etc? Level 1; Base codeline and meets level 0 requirements; Prototyped code, 3rd party tools, etc Level 2; Has Function Interface and comments and meets level 1 requirements; Sufficient documentation for each class and function; Able to determine functionality from comments Level 3; Adheres to coding standards and meets level 2 requirements; Follows defined coding standards and passes code checking utility test Level 4; Includes test cases and meets level 3 requirements; Has sufficient test cases to test all functionality of code Level 5; Approved by reuse committee and meets level 4 requirements; Reviewed by reuse experts and peers and verified it meets all levels of maturity I’m wondering if this maturity level should be a hierarchical structure, where in order to move to the next level you need to meet the requirements of all previous levels (as I have shown above)? Or if it should be a subset of requirements to meet the next level? For example, we have meet x out of y requirements, we can move to the next level (requirements would be the same as mentioned above). Level 0, meets 0 out of 6 requirements Level 1, meets 1 out of 6 requirements … The problem I see with the subset approach is some requirements should have a stronger weighting, and in this approach that will not be taken into account (unless I start getting specific like, meets a out of b and x out of y, etc). But then it could start to get complicated. Has anyone done this before, and if so, how did you setup your library? Do you have a maturity level at all or some other structure? Any input would be greatly appreciated.
Setting up a code reuse repository is a difficult task. The main difficulty is not in how you set it up but in how you communicate the existence of the various libraries in the repository. Reuse libraries only good if they are used, and they are only used if they are known, and they are only used widely if the quality of the code is high and if it meets the needs of the users. I like the idea of maturity levels, but as others have posted, there is probably quite a bit of setup/build work to do. I have thought of a similar approach to builds of an application - I called them confidence levels. In the application-build arena, a low confidence build is one that did not pass unit tests; a medium confidence might include passing unit tests, but not integration tests, and so on. This was a good mechanism for communicating to QA and users what to expect. A similar mechanism might be appropriate for libraries. Documentation comments are a must, and must also have as much care put into them as you put into the code. The comments should communicate what, why, where, when, how, which, etc. Your build process should publish the documentation to a well-known location (again, communication is key). Along the lines of communication, it doesn't hurt to present from time-to-time just what is there. Again! communication. So, at a minimum your build of each library should: publish the library (maybe notify subscribers) publish the documentation run unit tests publish the maturity level As to maturity levels, I would define them with a "level name" and a description of what the level means. Publish the criteria for what it means to move up or down a level. Actually, now that I think about it, perhaps you want a set of orthogonal criteria: a level for the code, a level for the documentation, use-policies (i.e. must have a license for XYZ), and other attributes. I do recommend you approach this in small increments though. At the end of the day, delivering functionality to end-users is what matters. You have to also communicate a mindset of naturally pushing reusable bits into the repository. Developers have to have incentive to do this usually. Static code checking tools that look for duplication and peer reviews only go so far. Someone has to actually do the work of moving code to the repository. Finally, I recommend that you use as much tool support as possible in the setup, build, maintenance, and communication of the repository. Otherwise, like any non-code artifact, you will face a certain amount of entropy which lowers the value as the non-code artifact becomes dated.
1,302,237
1,341,795
Marshalling CodeElements to an IntPtr in C#
I am writing a Visual Studio add in and need to marshall a managed CodeElements object to it's unmananged form. I just need the pointer in memory, as I can cast it and treat it like a CodeElement on the unmanaged side. [DllImport("CodeMethodsToString.dll")] private static extern BSTR* CodeMethodsToString(void* functionObject); public static void CodeMethodsToXML(XmlElement parent, CodeElements elements) { //Call CodeMethodsToString: how do I marshall CodeElements to an IntPtr? //set XmlElement in here } I know how to deal with the XML, and I have a working version of this in C#. I created the unmanaged DLL because calling all of the various member variables at the lowest level of recursion was killing the speed of the program. I simply need to know how to use System.Runtime.Interop.Marshal to convert the CodeElements object to a pointer to the COM object in memory. Thanks.
Looks like Jonathan was close. This is how I'd do it: [DllImport("CodeMethodsToString.dll")] [return: MarshalAs(UnmanagedType.BStr)] private static extern string CodeMethodsToString(IntPtr functionObject); public static void CodeMethodsToXML(XmlElement parent, CodeElements elements) { GCHandle pin; try { pin = GcHandle.Alloc(elements, GCHandleType.Pinned); string methods = CodeMethodsToString(pin.AddrOfPinnedObject()); } finally { pin.Free(); } }
1,302,347
1,302,408
Tree iterator, can you optimize this any further?
As a follow up to my original question about a small piece of this code I decided to ask a follow up to see if you can do better then what we came up with so far. The code below iterates over a binary tree (left/right = child/next ). I do believe there is room for one less conditional in here (the down boolean). The fastest answer wins! The cnt statement can be multiple statements so lets make sure this appears only once The child() and next() member functions are about 30x as slow as the hasChild() and hasNext() operations. Keep it iterative <-- dropped this requirement as the recursive solution presented was faster. This is C++ code visit order of the nodes must stay as they are in the example below. ( hit parents first then the children then the 'next' nodes). BaseNodePtr is a boost::shared_ptr as thus assignments are slow, avoid any temporary BaseNodePtr variables. Currently this code takes 5897ms to visit 62200000 nodes in a test tree, calling this function 200,000 times. void processTree (BaseNodePtr current, unsigned int & cnt ) { bool down = true; while ( true ) { if ( down ) { while (true) { cnt++; // this can/will be multiple statesments if (!current->hasChild()) break; current = current->child(); } } if ( current->hasNext() ) { down = true; current = current->next(); } else { down = false; current = current->parent(); if (!current) return; // done. } } }
Why not a recursive solution? void processTree (const BaseNodePtr &current, unsigned int & cnt ) { cnt++; if (current->hasChild()) processTree(current->child()); if (current->hasNext()) processTree(current->next()); } Since shared_ptr seems to be your bottleneck, why not improve it? Are you using threads? If not, then undefine the symbol BOOST_HAS_THREADS. The shared_ptr reference count is guarded by a mutex which is probably the cause of the slow performance. Why not change your data structure to not use shared_ptr altogether? Manage the raw pointers yourself? Maybe use scoped_ptr instead?
1,302,368
1,304,109
How to tell if OpenMP works in my C++ program
I am using OpenMP to do multithreading with my nested loops. Since new to this stuff, I am not sure if I am using OpenMP in the correct way so that it can actually do the parallel programming. So I like to know if I can measure the performance of my C++ program that uses OpenMP so I can tell it actually works and I am on the right track? Like how many threads are running in parallel and how long it takes for each of them to finish. Thanks and regards!
#include <omp.h> ... int target_thread_num = 4; omp_set_num_threads(target_thread_num); unsigned long times[target_thread_num]; // Initialize all the times #pragma omp parallel { int thread_id = omp_get_thread_num(); times[thread_id] = start_time(); std::cout << "Thread number: " << omp_get_thread_num() << endl; times[thread_id] = end_time(); } ... Obviously you need ot provide the two timer functions, but that's the gist. The OMP functions are pretty self-explanatory. Also make sure that your environment is set up properly and that you're compiling with the proper mechanisms. g++ option is -fopenmp. On Visual Studio go to project settings, C++, Language, and enable "OpenMP Support".
1,302,628
1,302,690
Tokyo Cabinet and variable size C++ objects
I'm building a system, with C++, that uses Tokyo Cabinet (original API in C). The problem is I want to store a class such as: class Entity { public: string entityName; short type; vector<another_struct> x; vector<another_struct> y vector<string> z; }; The problem is that vectors and strings have variable length. When I pass a void* (my object) to Tokyo Cabinet so it can store it, I also have to pass the size of the object in bytes. But that can't be trivially done. What is the best way to determine the number of bytes of an object? Or what is the best way to store variable length objects in Tokyo Cabinet. I'm already considering looking for serialization libs. Thanks
You cannot portably treat a non-POD C++ struct/class as a raw sequence of bytes - this is regardless of use of pointers or std::string and std::vector, though the latter virtually guarantee that it will break in practice. You need to serialize the object into a sequence of chars first - I'd suggest Boost.Serialization for a good, flexible cross-platform serialization framework.
1,302,785
1,302,877
"unresolved external symbol" for unreferenced function
I'm in Visual Studio 2003. I have a function in a very common module which requires 3 other modules. I want only projects using the new function to have to include the 3 other modules, and those that don't reference the function to link without "unresolved external symbol" errors. I tried function level linking, OPT:REF and every project setting I could think of, but the linker always complains. I made a simple example for testing. Any ideas would be awesome... //main.cpp //#include "a.h" int _tmain(int argc, _TCHAR* argv[]) { //a(); return 0; } //a.h #include "b.h" void a(); //a.cpp #include "a.h" #include "b.h" void a() { b(); } //b.h void b(); //b.cpp #include "b.h" void b() { } I need for the project to compile fine with only main.cpp and a.cpp in the project as long as a() is never called. If a() is called in _tmain(), then of course b.cpp would have to be added to the project. The linker doesn't seem to apply the OPT:REF until after it is sure EVERY function referenced ANYWHERE is in the project. Even if it (b()) is referenced in an unreferenced function (a()).
I have a function in a very common module which requires 3 other modules. I want only projects using the new function to have to include the 3 other modules, and those that don't reference the function to link without "unresolved external symbol" errors. It sounds to me that you should be separating this new function out into a different module. (Don't put it in the common module). That way, whoever needs it can include it, whoever doesn't, won't. Otherwise, you'll be stuck with some kind of conditional compilation macros that can only lead to trouble.
1,302,786
1,304,588
C++ IDE for Solaris SPARC
We've been given a C++ code base that was apparently developed using Rational Apex as the front end. In our opinion, Apex is less than ideal for C++ development. We're looking for an IDE we can use that has syntax highlighting, code-walking (go to definition, show usages), and isn't a pain to use. We've looked at NetBeans, Sun Studio and Understand. NetBeans is fighting us every step of the way, Sun Studio is lacking in features, and Understand is not really an IDE, but we're looking at trying to force it to be one with macros. There are other questions on SO that are similar, but they seem to be more directed questions (and more obscure). What I'd like to know is what Solaris developers use. Do we need to give NetBeans or Sun Studio another look, or is there something we missed?
Last time I was working on a Solaris codebase, I used Visual Studio. Yes, the Microsoft product. Modern versions of Both Visual Studio and Sun Studio are fairly standards compliant. As a result, I could debug application logic on Windows. For the low-level stuff we relied on Qt. As a bonus, once you've got the port to x86-64/Win done, supporting x86-64/Solaris becomes trivial.
1,302,974
1,303,002
How can I read from an std::istream (using operator>>)?
How can I read from an std::istream using operator>>? I tried the following: void foo(const std::istream& in) { std::string tmp; while(in >> tmp) { std::cout << tmp; } } But it gives an error: error: no match for 'operator>>' in 'in >> tmp'
Operator >> modifies stream, so don't pass by const, just a reference.
1,303,051
1,303,111
Has the STL changed much?
I'm wanting to become conversant in the use of the Standard Template Library. If I come across a general reference or beginner's guide published around 1995-97, can I rely on the information in it? How much has STL changed in the last dozen years?
Yes! There are new additions. The TR1 update is now implemented in most environments. Your older book is still useful to learn the basics. But you will want to find a reference for TR1 to learn about some very useful new features. In a couple of areas, the new features are preferred over older ones. (What comes to mind is bind1st and bind2nd functionality is fully encapsulated in the more general bind construct.) In addition, there are the boost libraries. (boost.org) Boost is a a collection of libraries, some are very useful, others are obscure. Some of the features in TR1 came from boost, so there is some overlap. There is at least one good book about Boost out there.
1,303,123
1,303,130
What is a handle in C++?
I have been told that a handle is sort of a pointer, but not, and that it allows you to keep a reference to an object, rather than the object itself. What is a more elaborate explanation?
A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it. For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense). EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.
1,303,890
1,303,910
derive problem about c++
Why I can't access base class A's a member in class B initialization list? class A { public: explicit A(int a1):a(a1) { } explicit A() { } public: int a; public: virtual int GetA() { return a; } }; class B : public A { public: explicit B(int a1):a(a1) // wrong!, I have to write a = a1 in {}. or use A(a1) { } int GetA() { return a+1; } }; class C : public A { public: explicit C(int a1):a(a1) { } int GetA() { return a-1; } };
A's constructor runs before B's, and, implicitly or explicitly, the former construct all of A's instance, including the a member. Therefore B cannot use a constructor on a, because that field is already constructed. The notation you're trying to use indicates exactly to use a constructor on a, and at that point it's just impossible.
1,303,899
1,303,915
Performance difference between ++iterator and iterator++?
My workmate claims that for object types preincrement is more efficient than post increment e.g. std::vector<std::string> vec; ... insert a whole bunch of strings into vec ... // iterate over and do stuff with vec. Is this more efficient than the next // loop? std::vector<std::string>::iterator it; for (it = vec.begin(); it != vec.end(); ++it){ } // iterate over and do stuff with vec. Is this less efficient than the previous loop? std::vector<std::string>::iterator it; for (it = vec.begin(); it != vec.end(); it++){ }
Postincrement must return the value the iterator had BEFORE it was incrementing; so, that previous value needs to be copied somewhere before altering it with the increment proper, so it's available to return. The extra work may be a little or a lot, but it certainly can't be less than zero, compared to a preincrement, which can simply perform the incrementing and then return the just-altered value -- no copying // saving // etc necessary. So, unless you specifically MUST have postincrement (because you're using the "value before increment" in some way), you should always use preincrement instead.
1,303,947
1,303,966
C++ compiler warning - returning local variable
I'm simply trying to overload a + operator and I'm getting this compiler warning reference to local variable 'tmp' returned Here is the code for the overload const Int& Int::operator+(const Int& p) const { Int tmp = value + p.value; return tmp; } Here is the class class Int{ int value; public: Int() {} // default constructor Int(int v) : value(v) {} Int& operator=(const Int&); const Int& operator+(const Int&) const; };
You can't return a reference to a local variable. Inside the operator+() function, you're creating a local variable called tmp. It will get destroyed as soon as the function exits. You can't return a reference to that variable, because it no longer exists when the calling function gets the return value. Change your definition of the function to: const Int operator+(const Int&) const; It would build without warnings and work fine too.
1,303,993
1,304,166
Pre-allocate space for C++ STL queue
I'm writing a radix sort algorithm using queues and I would like to have a STL queue allocate space before I start adding things to the queue so that I can avoid constant dynamic resizing operations. Even though this doesn't exist, I want something with the effect of... queue<int> qs(N); for(int i=0;i<N;++i) qs.push(rand()); in such a way that it will not dynamically allocate any memory during the loop. The actual code in question... void radix_sort() { // Biggest number? int max=-1; for(int i=0;i<N;++i) if(a[i]>max) max = a[i]; // How many digits in it int maxdigits=1; while(max /= 10) maxdigits++; // Create some buckets. deque<int> b[10]; for(int i=0;i<10;++i) b[i] = deque<int>(N); int div=1; // Radix Sort by digits for(int d=1;d<=maxdigits;++d) { if(d>1) div*=10; // Queue for(int i=0;i<N;++i) b[ (a[i]/div) % 10 ].push_front(a[i]); // Dequeue int k=0; for(int q=0;q<10;++q) while(b[q].size() > 0) { a[k++] = b[q].back(); b[q].pop_back(); } } }
Chances are this is not a problem. Deque's allocate in chunks anyway, so you'll probably only reallocate a few times. Have you determined this to be a bottleneck? Anyway, the standard does not give an accessor to the `queue''s container, because that would defeat the purpose of encapsulation. If you're really worried, pool allocate. This means preallocate the memory upfront, so when the container asks for memory, it's already there. I can't really go over allocators and kin, that would be overkill for an SO answer, but look up allocators on Google. Basically, you can tell your container where to get it's memory from. Normally, this is the default allocator, which uses new and delete. Boost provides a pool allocator, and it would go something like this: #include <list> #include <queue> // pool #include <boost/pool/pool_alloc.hpp> // helpful typedef's typedef boost::fast_pool_allocator<int> BoostIntAllocator; typedef boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(int)> BoostIntAllocatorPool; int main(void) { // specify the list as the underlying container, and inside of that, // specify fast_pool_allocator as the allocator. by default, it preallocates // 32 elements. std::queue<int, std::list<int, BoostIntAllocator > > q; /* No memory allocations take place below this comment */ for (int i = 0; i < 31; ++i) { q.push(i); } /* End no allocation */ // normally, the memory used by the singleton will // not be free'd until after the program is complete, // but we can purge the memory manually, if desired: BoostIntAllocatorPool::purge_memory(); }; The pool allocates the memory up-front, so no actual memory allocation is done during push()/pop(). I used a list instead of a deque because it is simpler. Normally, a deque is superior to a list, but with an allocator, the things that gave the deque it's advantage, like cache-performance and allocation cost, no longer exist. Therefore, a list is much simpler to use. You can also use a circular buffer, like such: #include <queue> // ring #include <boost/circular_buffer.hpp> int main(void) { // use a circular buffer as the container. no allocations take place, // but be sure not to overflow it. this will allocate room for 32 elements. std::queue<int, boost::circular_buffer<int> > q(boost::circular_buffer<int>(32)); /* No memory allocations take place below this comment */ for (int i = 0; i < 31; ++i) { q.push(i); } /* End no allocation */ };
1,304,035
1,304,092
Access member function of another .cpp within same source file?
I am working in Visual C++. I have two .cpp files in the same source file. How can I access another class (.cpp) function in this main .cpp?
You should define your class in a .h file, and implement it in a .cpp file. Then, include your .h file wherever you want to use your class. For example file use_me.h #include <iostream> class Use_me{ public: void echo(char c); }; file use_me.cpp #include "use_me.h" //use_me.h must be placed in the same directory as use_me.cpp void Use_me::echo(char c){std::cout<<c<<std::endl;} main.cpp #include "use_me.h"//use_me.h must be in the same directory as main.cpp int main(){ char c = 1; Use_me use; use.echo(c); return 0; }
1,304,040
1,304,071
C++ Constant Expression and Array Bounds
Can someone please explain (what might be my perceived) disparity in errors in the following code? Essentially why are "//OK" okay and "//error" errors? (Compiler is i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5490)) #include <cmath> #include <iosfwd> template <typename T> class TT{ char _c[sizeof(T) + static_cast<size_t>(::ceil(sizeof(T) * 0.001)) + 1]; // error: array bound is not an integer constant //char _c[sizeof(T) + static_cast<size_t>(sizeof(T) * 0.001) + 1]; // OK T _t; }; class IS{ unsigned char* _u; double _d; }; char s[static_cast<size_t>(::ceil(sizeof(TT<IS>) * 10.0))]; // error: array bound is not an integer constant int main(int argc, char** argv){ char a[static_cast<size_t>(10.0)]; // OK char b[static_cast<size_t>(::ceil(sizeof(double) * 10.0))]; // OK TT<int> it; char c[static_cast<size_t>(::ceil(sizeof(TT<int>) * 10.0))]; // OK TT<IS> is; char d[static_cast<size_t>(::ceil(sizeof(TT<IS>) * 10.0))]; // OK return 0; } As a side note, I am aware of C++0x: Generalized constant expression.
The problem is in where the arrays are declared. You can's declare an array with non-constant size at file level since the compiler needs to know at compile time how much to allocate and in your case this would require a function call. When you do the same at function level the C++ extension your compiler supports kicks in (this is not allowed by the standart) – the compiler emits code that will call the function, compute the value and allocate the array on stack in runtime.
1,304,174
1,304,186
How to strip debug code during compile time in C++?
Say I have a C++ function debugPrint(int foo). How can I most conveniently strip that from release builds? I do not want to surround every call to debugPrint with #ifdefs as it would be really time consuming. On the other hand, I want to be 100% sure that the compiler strips all the calls to that function, and the function itself from release builds. The stripping should happen also, if it's called with a parameter that results from a function call. E.g., debugPrint(getFoo());. In that case I want also the getFoo() call to be stripped. I understand that function inlining could be an option, but inlining is not guaranteed to be supported.
Use conditinal compilation and a macro: #ifdef _DEBUG #define LOG( x ) debugPrint( x ) #else #define LOG( x ) #endif Define _DEBUG for the debug build and not define it for the release build. Now in release build every LOG( blahbhahblah ); will be expanded into an empty string - even the parameters will not be evaluated and will not be included into the emitted code. You can use any already existing preprocessor symbol that is defined in debug build and not defined in release instead of _DEBUG.
1,304,187
1,304,482
How to convert a vector<pair<int,int> > to multimap<int,int> efficiently?
How to convert a multimap<int,int> to vector<pair<int,int> > efficiently EDIT: Sorry for the trouble I was actually looking for converting vector to map
The value type of a multimap<int,int> is pair<int,int> - exactly what you would like your vector to hold. So, you can use the constructor to initialize the vector from the multimap: std::vector< std::pair<int,int> > v( mmap.begin(), mmap.end() ); Or, if you have an existing vector where you want to copy the elements: v.resize( mmap.size() ); std::copy( mmap.begin(), mmap.end(), v.begin() ); You can also use the std::back_inserter, but that would be slower in general due to vector reallocations: std::copy( mmap.begin(), mmap.end(), std::back_inserter(v) ); EDIT To answer your other question - you can convert a vector to a multimap in a similar way. The multimap also has a constructor which accepts an iterator range: std::multimap<int,int> mmap(v.begin(), v.end()); This, of course, assumes that v is std::vector< std::pair<int,int> >.
1,304,680
1,304,785
Object slicing with private copy constructor in derived class in C++
Suppose I have something like the following in test.cxx (and that I do the object slicing at 1 intentionally): class A { }; class B : public A { // prevent copy construction and assignment B(const B& other); B& operator=(const B& other); public: explicit B(){} }; class C { A m_a; public: explicit C() : m_a( B() ) {} // 1 }; I expect this to work, as in 1 the copy-constructor of class A (here it is compiler-generated and public) should be called. This code also compiles fine on recent compilers (I tried g++-4.4 and Intel 11.0), however older compilers (such as g++-4.2 and g++-4.0) try to invoke the copy-constructor of B, which I declared to be private, resulting in: test.cxx: In constructor ‘C::C()’: test.cxx:7: error: ‘B::B(const B&)’ is private test.cxx:16: error: within this context Now, in my build-system I want to check whether the compiler supports above code. Question is, however, is this standard-conforming code? And what would be the proper name for such a test? Edit: I'm sorry, Intel compiler version 10.1 and 11.0 both issue the following: warning #734: "B::B(const B &)" (declared at line 6), required for copy that was eliminated, is inaccessible
I dare to disagree with Comeau in this case. In fact, the following code fails to compile as expected, because binding an rvalue to a const reference requires accessible copy constructor. class A { }; class B : public A { B(const B& other); B& operator=(const B& other); public: explicit B(){} }; int main() { A const & a = B(); } Per 8.5.3/2, "[...] Argument passing (5.2.2) and function value return (6.6.3) are initializations," and as such the code should be ill-formed. Edit: I still firmly believe that the code is ill-formed according to C++03. However, I've just read the relevant section of the working draft for C++0x and it seems that it no longer requires the copy constructor to be available. Perhaps that's the reason your code started compiling when you moved from gcc-4.2 to gcc-4.3. Edit: To clarify, the reason why B::B(const B &) must be accessible is due to the binding of B() to the first parameter of A::A(const A &) (which is, of course, called when m_a is being initialized). Edit: Regarding the difference between C++03 and C++0x, litb was kind enough to find the relevant defect report.
1,304,723
1,304,901
template function specialization problem
I am using templates to implement a range checked conversion from int to enum. It looks like this: template<typename E> E enum_cast(const int &source); The template function placed more or less in the root-directoy of the project. When defining a new enum that is foreseen to be assigned values from a config file like this: enum ConfigEnum { ConfigEnumOption1 = 'A' , ConfigEnumOption2 = 'B' , ConfigEnumInvalid }; ConfigEnum option = XmlNode.iAttribute("option"); I define a template specialization for this particular enum type in a .cpp-file for the module this enum is used in. template<> ConfigEnum enum_cast(const int &source) { switch(source) { case ConfigEnumOption1 : return ConfigEnumOption1; case ConfigEnumOption2 : return ConfigEnumOption2; default return ConfigEnumInvalid; } Now the assignment of an int to the enum becomes: ConfigEnum option = enum_cast<ConfigEnum>(XmlNode.iAttribute("option")); which makes sure that the enum is allways in valid range. Note that I have not allways control over these enums so this seems to a be reasonable and easily configureable solution. Anyway, this works all very well (although I am not shure all code given here is correct because I just recall it from memory right now) The problem stems from the fact that it might be desireable to use this "enum_cast" construct thorughout the code base whenever an in is assigned to a enum. After all this can be enforced by a simple search-and-replace operation. Of course I do not want to define these specializations for all and every enum around but only for those that need the range check at the moment. I would prefer to add template specializations for the enum types when the need arises and use the assignment operator when no specialization is defined. Thus: InternalEnum internal = enum_cast<InternalEnum>(internal_integer); would effecively call internal = internal_integer. I figure that I need to tell the compiler to use a certain "default" implementation for all enum types that do not have a specialization. My first bet was giving the original template function an implementation like this: template<typename E> E enum_cast(const int &source) { E copy = source; return copy; }; Unfortunately now this is allways called instead of the specialiazations given in the .cpp-files deeper into the project directory-tree. Any thoughts? Thanks in advance Arne
The explicit specializations have to be visible everywhere they are used. And as they are definitions, they can't be repeated in every compilation unit. So in the header file where you define an enum you want to check you say #include "enum_cast.h" enum Foo { Foo_A, Foo_B, Foo_C }; template<> Foo enum_cast<Foo>(int source); and in the corresponding .cpp you give the definition.
1,304,736
1,304,831
reinterpret_cast to void* not working with function pointers
I want to reinterpret cast a function pointer into a void* variable. The type of the function pointer will be of type Class* (*)(void*). Below is the sample code, class Test { int a; }; int main() { Test* *p(void **a); void *f=reinterpret_cast<void*>(p); } The above code works well with Visual Studio/x86 compilers. But with ARM compiler, it gives compilation error. Don't know why. Error: #694: reinterpret_cast cannot cast away const or other type qualifiers I read the explanation in Casting a function pointer to another type I was concerned about the below explanation. Casting between function pointers and regular pointers (e.g. casting a void (*)(void) to a void*). Function pointers aren't necessarily the same size as regular pointers, since on some architectures they might contain extra contextual information. This will probably work ok on x86, but remember that it's undefined behavior. How to do such conversions from void (*)(void*) -> void* effectively so that atleast it compiles almost the same in most of the compilers ?
reinterpret_cast can't be used to cast a pointer to function to a void*. While there are a few additional things that a C cast can do which aren't allowed by combination of static, reinterpret and const casts, that conversion is not one of them. In C the cast is allowed, but it's behavior isn't defined (i.e. even round trip isn't guaranteed to work). Some POSIX functions need the conversion to be well useful. I've played with several compilers I've here: none prevent the C cast, even in the highest conformance mode. Some give a warning depending on the warning and conformance level, others gave no warning whatever I tried. the reinterpret_cast was a error with some compilers even in the more relaxed level while other accepted it in all case without ever giving a warning. In the last available draft for C++0X, the reinterpret_cast between function pointers and objects pointers is conditionally supported. Note that if that make sense or not will depend on the target more than the compiler: a portable compiler like gcc will have a behavior imposed by the target architecture and possibly ABI. As other have make the remark, Test* *p(void **a); defines a function, not a pointer to function. But the function to pointer to function implicit conversion is made for the argument to reinterpret_cast, so what reinterpret_cast get is a Test** (*p)(void** a). Thanks to Richard which makes me revisit the issue more in depth (for the record, I was mistaken in thinking that the pointer to function to pointer to object was one case where the C cast allowed something not authorized by C++ casts combinations).
1,304,737
1,304,752
How is *array* memory allocated and freed in C and C++?
My question specifically is in regards to arrays, not objects. There a few questions on SO about malloc()/free() versus new/delete, but all of them focus on the differences in how they are used. I understand how they are used, but I don't understand what underlying differences cause the differences in usage. I often hear C programmers say that malloc() and free() are costly operations, but I've never heard a C++ programmer say this about new and delete. I've also noticed that C++ doesn't have an operation that corresponds to C's realloc(). If I were writing an equivalent to C++'s vector class, I would want to avoid copying the entire array when resizing it, but with new and delete you have to copy. In C, I would simply realloc(). It's worth noting that realloc() might just copy the entire array, but my impression was that it used the same pointer and allocated less space for it, at least when sizing down. So my question is, how do the algorithms used by malloc() and free() differ from those used by new and delete. More specifically, why does the C way have a stigma of being more expensive, and why doesn't the C++ way allow resizing without copying?
There's no real difference under the hood - usually the default new and delete operators will simply call through to malloc and free. As for "the stigma of being more expensive", my theory is this: back in the day, every cycle counted, and the time taken by malloc really was significant in many situations. But by the time C++ came along, hardware was much faster and the time taken by the free store manager was proportionally less significant. The emphasis was shifting from efficient use of machine resources to efficient use of programmer resources. Why C++ lacks a realloc equivalent, I don't know.
1,304,771
1,304,804
C and C++: Freeing PART of an allocated pointer
Let's say I have a pointer allocated to hold 4096 bytes. How would one deallocate the last 1024 bytes in C? What about in C++? What if, instead, I wanted to deallocate the first 1024 bytes, and keep the rest (in both languages)? What about deallocating from the middle (it seems to me that this would require splitting it into two pointers, before and after the deallocated region).
If you have n bytes of mallocated memory, you can realloc m bytes (where m < n) and thus throw away the last n-m bytes. To throw away from the beginning, you can malloc a new, smaller buffer and memcpy the bytes you want and then free the original. The latter option is also available using C++ new and delete. It can also emulate the first realloc case.
1,304,847
1,304,956
Is it possible to lower the privilege level when calling CoCreateInstance on Vista?
Okay, I have a plugin for IE that when installed needs to (with the user's permission) restart IE. To do this I have a DLL that is invoked by the installer. And it works, but the problem is that when IE is restarted on Vista, it is restarted with the administrator privileges of the installer, which is a problem for a number of reasons. I'm using CoCreateInstance to start IE, so that I get an instance of the IWebBrowser2 interface in order to perform some actions on it. So my question is, is it possible to call CoCreateInstance from an application that is running with Administrator privileges, in such a way that the resulting COM object instance inherits the base user privileges rather than the administrator privileges of the calling application?
Okay, I found the solution from here: http://social.msdn.microsoft.com/Forums/cs-CZ/ieextensiondevelopment/thread/78a2bc18-1920-4e58-af7e-48dbcebe7643 From my installer DLL I need to launch a new thread, and impersonate the current user on that thread, and then set a low integrity level, and create the COM instance with the CLSCTX_ENABLE_CLOAKING context.
1,305,055
1,305,152
Reference initialization in C++
Greetings, everyone! Examining my own code, I came up to this interesting line: const CString &refStr = ( CheckCondition() ) ? _T("foo") : _T("bar"); Now I am completely at a loss, and cannot understand why it is legal. As far as I understand, const reference must be initialized, either with r-value or l-value. Uninitialized references cannot exist. But ()? operator executes a CheckCondition() function before it assigns value to the reference. I can see now, that while CheckCondition() is executed, refStr exists, but still not initialized. What will happen if CheckCondition() will throw an exception, or pass control with a goto statement? Will it leave the reference uninitialized or am I missing something?
Simpler example: const int x = foo(); This constant too has to be initialized, and for that foo() needs to be called. That happens in the order necessary: x comes into existance only when foo returns. To answer your additional questions: If foo() would throw, the exception will be caught by a catch() somewhere. The try{} block for that catch() surrounded const int x = foo(); obviously. Hence const int x is out of scope already, and it is irrelevant that it never got a value. And if there's no catch for the exception, your program (including const int x) is gone. C++ doesn't have random goto's. They can jump within foo() but that doesn't matter; foo() still has to return.
1,305,132
1,305,149
crash when calling library
Let's hope I can dumb this down without leaving out crucial details... I've got a test program: #include <lib.h> const char * INPUT = "xyz"; int main() { initializeLib(); LibProcess * process = createLibProcess(); fprintf( stderr, "Before run(%s)\n", INPUT ); process->run(INPUT); fprintf( stderr, "After run(%s)\n", INPUT ); return 0; } This test program I compile (gcc 4.1.2) and run as: g++ -g -o test test.c -L /path/to/lib -I /path/to/include -lnameoflib export LD_LIBRARY_PATH=/path/to/lib ./test The library is rather complex, and not-too-smart in some places, and most importantly not-written-by-me, so don't flame me for the architecture of the functions involved: class ProcessBase { public: virtual int run( const char* buffer = NULL ) = 0; } class LibProcess : ProcessBase { public: LibProcess() { fprintf( "Reached LibProcess().\n" ); } int run( const char* buffer = NULL ) { fprintf( stderr, "Reached run().\n" ); } }; void initializeLib() { // Preparing some data } ProcessBase * createLibProcess() { ProcessBase * process = new LibProcess(); fprintf( stderr, "Created Process.\n" ); return (ProcessBase *) process; } So far, so good. But the output of it really had me baffled: Reached LibProcess(). Created Process. Before run(xyz) SEGFAULT I know the error is (most likely) somewhere completely different. But how is this at all possible? I would understand if the test died on calling the library the first time. I would understand if the test died when creating the process, or when it actually does something in run(). But how can it die between the calling of the function and actually reaching that function? I'm clueless, especially I don't know how to continue debugging this. Help? Edit: Yes, I checked process to have a non-NULL value after createLibProcess(). A subsequent call to two different member functions of process, left out of the example, also worked beautifully. But the second member function call trashed memory due to a buffer overflow, and zeroed process. This makes the question invalid. Of course is calling NULL->run() a segfaulting offense. Question can be closed as "no longer relevant". Thanks anyway!
Is process definitely set to a non-NULL valid pointer before it is dereferenced to call run?
1,305,422
1,305,470
How to make a string preprocessor definition from command-line in VC 2005 (C++)?
The documentation tells me that /D command-line switch can be used to do this, like so: CL /DDEBUG TEST.C would define a DEBUG symbol, and CL /DDEBUG=2 TEST.C would give it the value 2. But what do I do if I would like to get the equivalent of a string define, such as #define DEBUG "abc" ?
Due to the way command line is parsed in Windows, you'll have to escape the quotes. CL /DDEBUG=\"abc\" TEST.C
1,305,493
1,306,713
Debug DLL's under Windows with GDB
I have some project consisting of a couple of DLL's which have been compiled with MinGW with debug information, and another project with EXE target which uses these DLLs (compiled with MinGW too). The problem is, I need to put breakpoints on functions inside those DLLs, but GDB, although sets them, just silently ignores them at runtime. Stepping into them (with 's' key) just skips them over (like with an 'n' key). How can I get inside those DLLs? Maybe there's some option I should specify to GDB? Thanks in advance.
Make sure you are compiling with gcc optimization level flag setted to 0 ( -O0 ).
1,305,502
1,368,792
Designing efficient C++ code for fibers
How do I utilize fibers best in my game code? Should it only be used to manage nonpreemptive context-switches while loading resources (i.e. files from disk)? Or do I allow all types of game entities to run in a fiber? How do I schedule? C++ or pseudo code samples greatly appreciated!
Don't? It's like a thread only with very little CRT support (unlike threads) and some hidden memory requirements like stack and registers. It may make non-system code easier to write but it complicates to an unjustifiable degree.
1,305,713
1,305,725
How do ensure that while writing C++ code itself it will not cause any memory leaks?
Running valgrind or purify would be the next steps But while while writing the code itself how do you ensure that it will not cause any memory leaks? You can ensure following things:- 1: Number of new equal to delete 2: Opened File descriptor is closed or not Is there any thing else?
Use the RAII idiom everywhere you can Use smart pointers, e.g. std::auto_ptr where appropriate. (don't use auto_prt in any of the standard collections as it won't work as you think it will)