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,095,705
1,095,752
Using Boost::ref correctly..?
How can I get this to compile? The error is when I start using boost::ref(). I thought boost::ref is used to pass reference to C++ algorithm classes? list<Object> lst; lst.push_back(Object(1,2.0f)); lst.push_back(Object(3,4.3f)); struct between_1_and_10 { int d; void operator() (Object& value) {...
This what you really want: for_each(lst.begin(), lst.end(), boost::bind<void>(boost::ref(val),_1 ) ); EDIT: Some explanation upon the OP's request. Recall that for_each() takes a function, but you were merely passing it a reference to your struct (yes, the struct has it's operator() overloaded but you were not passin...
1,096,072
1,096,080
Convert struct to unsigned char *
How can I convert the following struct to unsigned char*? typedef struct { unsigned char uc1; unsigned char uc2; unsigned char uc3; unsigned char uc5; unsigned char uc6; } uchar_t; uchar_t *uc_ptr = new uchar; unsigned char * uc_ptr2 = static_cast<unsigned char*>(*uc_ptr); // invalid static cast at...
You can't use a static_cast here since there is no relationship between the types. You would have to use reinterpret_cast. Basically, a static_cast should be used in most cases, whereas reinterpret_cast should probably make you question why you are doing it this way. Here is a time where you would use static_cast: clas...
1,096,207
1,096,224
C++: Replacing part of string using iterators is not working
I am writing a simple program, which is trying to find next palindrome number after given number. As for now, I am stuck at this point: string::iterator iter; // iterators for the string string::iterator riter; //testcases is a vector<string> with strings representing numbers. for (unsigned int i = 0; i < testcases....
About the code you have: Why don't you just assign the values at the end of the two iterators? if ( *iter != *riter ) { *riter = *iter; } As Oli pointed out, there are other problems in the code, the first of which is the fact that you are setting riter to be string.end(), witch is a non-dereference-able iterator. ...
1,096,291
1,096,358
How to format my own objects when using STL streams?
I want to output my own object to a STL stream but with customized formatting. I came up with something like this but since I never used locale and imbue before I have no idea if this makes sense and how to implement MyFacet and operator<<. So my questions are: does this make sense and how to implement MyFacet and oper...
Well, a locale is generally used to allow different output/input formatting of the same object based on the local (the specified locale in fact) formatting which is present. For a good article on this see: http://www.cantrip.org/locale.html. Now maybe its because your example above is quite simplified, but to me it loo...
1,096,341
1,096,349
Function pointers casting in C++
I have a void pointer returned by dlsym(), I want to call the function pointed by the void pointer. So I do a type conversion by casting: void *gptr = dlsym(some symbol..) ; typedef void (*fptr)(); fptr my_fptr = static_cast<fptr>(gptr) ; I have also tried reinterpret_cast but no luck, although the C cast operator see...
Converting a void* to a function pointer directly is not allowed (should not compile using any of the casts) in C++98/03. It is conditionally supported in C++0x (an implementation may choose to define the behavior and if it does define it, then it must do what the standard says it should do. A void*, as defined by th...
1,096,482
2,147,201
How to access Firefox's DOM (or HTML content) from outside firefox
I have a question: My program will search FireFox windows opened by user. When a user open Firefox and enter any site, I want to search for a keyword in that page's HTML content. How can I access Firefox's Active Tab's DOM (or HTML content) from outside firefox using my C++ program. Is it possible? If so, can you give ...
There is no built-in way to access the DOM of a web page inside Firefox from an external program. You can write an extension that implements some sort of IPC (using sockets or whatever) and communicate with that, but not built-in to Firefox.
1,096,615
1,096,648
Automatic Java to C++ conversion
Has anyone tried automatic Java to C++ conversion for speed improvements? Is it a maintenance nightmare in the long run? Just read that is used to generate the HTML5 parsing engine in Gecko http://ejohn.org/blog/html-5-parsing/
In general, automatic conversions from one language to another will not be an improvement. Different languages have different idioms that affect performance. The simplest example is with loops and variable creation. In a Java GC world, creating objects with new is almost free, and they dive into oblivion just as easily...
1,096,700
1,096,743
Instantiate class from name?
imagine I have a bunch of C++ related classes (all extending the same base class and providing the same constructor) that I declared in a common header file (which I include), and their implementations in some other files (which I compile and link statically as part of the build of my program). I would like to be able...
This is a problem which is commonly solved using the Registry Pattern: This is the situation that the Registry Pattern describes: Objects need to contact another object, knowing only the object’s name or the name of the service it provides, but not how to contact it. Provide a service that takes the...
1,096,931
1,097,215
Overloaded member function pointer to template
I'm trying to store member function pointers by templates like this: (This is a simplified version of my real code) template<class Arg1> void connect(void (T::*f)(Arg1)) { //Do some stuff } template<class Arg1> void connect(void (T::*f)()) { //Do some stuff } class GApp { public: void foo() {} ...
Your code as written doesn't compile. I've make some "assumptions" about what you wanted to do, and have changed the code. To summarise, you can call the correct function by explicitly specifying the function parameter type: connect<double> (&GApp::foo); If the connect methods are members of a class template, then it...
1,097,062
1,097,225
How does visual studio know which cpp files to rebuild when an include file is changed?
In some of my VS 2005 projects, when I change an include file some of the cpp files are not rebuilt, even though they have a simple #include line in them. Is this a known bug, or something strange about the projects? Is there any information about how VS works out the dependencies and can I view the files for that? bt...
I've experienced this problem from time to time, and with other IDEs too, not just VS. It seems thatv their internal dependency tree sometimes gets out of whack with reality. In these cases, I've found deleting pre-compiled headers (this is important) and doing a complete rebuild always solves the problem. Luckily, it...
1,097,126
1,106,420
Implement user activity logger in old application?
How to go about implementing a user activity logger in MFC application.To get to know what are all the features are used most in an existing application.
You can override the windows procedure of your application window: class CMyMainWindow { void LogUsageData(UINT message); virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { LogData(message); return CWnd::WindowProc(message, wParam, lParam); // route message to message m...
1,097,185
1,097,194
What is the simplest way to write a timer in C/C++?
What is the simplest way to write a timer in C/C++? Hi, What is the simplest way to write a timer, say in C/C++? Previously I used a for loop and a do-while loop. I used the for loop as a counter and the do-while loop as a comparison for "end of time". The program worked as I wanted it to, but consumed too much system ...
Your best bet is to use an operating system primitive that suspends the program for a given amount of time (like Sleep() in Windows). The environment where the program will run will most likely have some mechanism for doing this or similar thing. That's the only way to avoid polling and consuming CPU time.
1,097,236
1,097,413
pthread_cond_timedwait linking error with clock_gettime on Solaris 10
I have a bit of code which used pthread_cond_wait which looks like this: struct timespec ts; clock_getttime(CLOCK_REALTIME, &timS); ts.tv_sec += delay; pthread_mutex_lock(&a_mutex); pthread_cond_timedwait(&thread_cond, &a_mutex,&timS); pthread_mutex_unlock(&a_mutex); But I get a linker error on compilation, un...
The -lc answer is wrong. You need to add -lrt (presumably real time..?)
1,097,479
1,098,357
Name resolution in templates
I was reading about the template name resolution here. Just to get the feel of the things I replicated the code like this: void f (char c) { std::cout<<"f(char)\n"; } template <class T> void g(T t) { f(1); f(T(1)); f(t); d++; } double d; void f(int n) { std::cout<<"f(int)\n"; } void test() { ...
Also for the first call of g(1), I should have one call of f(char) followed by two calls of f(int) and for the second call I should get three calls of f(char). This is not the expected result with a Standard compliant compiler. Since both time you call it with a fundamental type, you will not get name lookup at the i...
1,097,576
2,873,703
Load Excel data into Linux / wxWidgets C++ application?
I'm using wxWidgets to write cross-plafrom applications. In one of applications I need to be able to load data from Microsoft Excel (.xls) files, but I need this to work on Linux as well, so I assume I cannot use OLE or whatever technology is available on Windows. I see that there are many open source programs that can...
I can say that I know of a wxWidgets application that reads Excel .xls and .xlsx files on any platform. For the .xlsx files we used an XML parser and zip stream reader and grab the data we need, pretty easy to get going. For the .xls files we used: ExcelFormat, which works well and we found the author to be very genero...
1,097,579
1,103,912
How do I get the VS debugger to display the type name of an object member?
The Visual Studio autoexp.dat syntax allows you to display ‘the name of the most-derived type of the object’ with the 'special format' <,t>, which is very helpful if you have lots of derived types. From the syntax, I assumed that you could do the same thing for members, such as <member,t>, but when I try that the previ...
I have found a way to do it, but it's not a very elegant solution: Write an [AutoExpand] entry for the member type which includes the <,t> directive. Then when you display the member with <member> it will show the same information as it does for the member type on its own, including its type name. It's not a great solu...
1,097,733
1,097,751
How to Convert Address to Function Pointer to Call Method
I wanted to call Test1() Method Within WaitAndCallFunc() Function. Code: typedef void (*func)(); void StartTimer(void* pFuncAddr); void WaitAndCallFunc(void* pPtr); void WaitAndCallFunc(void* pPtr) { int i = 0; int nWaitTime = 3; while(1) { Sleep(1000); // I want pPtr to call Test1 Funct...
I'm not sure I understand what your question is exactly, but try this: ((func)pPtr)();
1,097,771
1,098,968
getsockopt() returns EINPROGRESS in non blocking connect()+select() flow
Update: My bad. The error I am getting is ECONNREFUSED and not EINPROGRESS. After checking the error variable I've found that it is greater than 0, I printfed errno instead of error. Of course errno is EINPROGRESS because it value didn't change since the call to connect(). Question answered. Thanks folks. I am using t...
Shucks....I give up. I tried and tried but could not find a problem with your code. So, all I offer are some suggestions and hypothesis. Use FD_COPY to copy rset to wset. Can you do a getsockopt when the first connect fails. I am suspecting that Select is returning 0 and because of above, somehow your writefd set is...
1,097,785
1,097,861
start exe as non admin from admin exe
When my app updates it needs admin rights and pops the uac prompt up and this is all good. However when it restarts it self its still in admin mode and thus every thing it does has admin rights. The problem comes when the next time the app is started its a normal user and thus cant read any of the files that where made...
Here is an article that describes how to start non-elevated process from an elevated one.
1,097,880
1,097,915
reading bytes directly from RAM C++
Can anyone explain the following behaviour to a relative newbie... const char cInputFilenameAndPath[] = "W:\\testerfile.bin"; int filesize = 4584; char * fileinrampointer; fileinrampointer = (char*) malloc(filesize); ifstream fsInputFileStream; fsInputFileStream.open(cInputFilenameAndPath, fstream::in | fstream::bina...
The expression *fileinrampointer is of type signed char, and it is being promoted to a signed int while being passed to printf. Thus, the sign bit propagates. Later on, you print it out with %x which means unsigned int in hex, which causes you to print all the 1's (as opposed to correctly interpret them as a part of a ...
1,097,969
1,097,989
How can web technology be used for a C++ application GUI?
Can web technologies be used for a desktop application written in a traditional language like C++? I'd guess that they can, though I've not been able to find any evidence of this. I understand Adobe Air can make desktop apps using Flash, but it uses web languages like php etc. What I'd like to do is to be able to build...
Qt is moving in this direction, with CSS-like styling and a forthcoming "declarative" UI mechanism. In addition, you can drive your app with Javascript via QtScript. You could also use QtWebKit to provide an HTML based UI, it's possible to bridge between C++ code and Javascript too.
1,098,303
1,098,875
What makes Scala's operator overloading "good", but C++'s "bad"?
Operator overloading in C++ is considered by many to be A Bad Thing(tm), and a mistake not to be repeated in newer languages. Certainly, it was one feature specifically dropped when designing Java. Now that I've started reading up on Scala, I find that it has what looks very much like operator overloading (although tec...
C++ inherits true blue operators from C. By that I mean that the "+" in 6 + 4 is very special. You can't, for instance, get a pointer to that + function. Scala on the other hand doesn't have operators in that way. It just has great flexibility in defining method names plus a bit of built in precedence for non-word s...
1,098,723
1,105,742
Eclipse-CDT: Whats the best way to add a custom build step?
I have a file in my project which I need to compile using an external tool, and the output of that is a pair of .c and .h files. Whats the best way to integrate this into my Eclipse-CDT build? Ideally I can reference the external tool using a relative path Ideally Eclipse will know if I change this file that it needs ...
I got this working well by adding a 'Builder' of type 'Program'. Right click on the project, Click Properties, Click New ..., Add the location of the file you want to execute, as well as any command line arguments.
1,098,752
1,098,773
Forward "Pre-declaring" a Class in C++
I have a situaion in which I want to declare a class member function returning a type that depends on the class itself. Let me give you an example: class Substring { private: string the_substring_; public: // (...) static SubstringTree getAllSubstring(string main_string, int min_size); }...
You could define it inside the class: class Substring { private: string the_substring_; public: // (...) typedef set<Substring, Substring::Comparator> SubstringTree; static SubstringTree getAllSubstring(string main_string, int min_size); };
1,098,966
1,099,080
Universal less<> for pointers in C++ standard
Many times I needed a set of pointers. Every time that happens, I end up writing a less<> implementation for a pointer type - cast two pointers to size_t and compare the results. My question is - is that available in the standard? I could not find anything like that. Seems like common enough case... Update: it seems th...
Two pointers can be compared with using the comparison function objects less, greater etc. Otherwise, using blanket operator< etc, this is only possible if the pointers point to elements of the same array object or one past the end. Otherwise, results are unspecified. 20.3.3/8 in C++03 For templates greater, less, g...
1,099,208
1,099,214
if - else vs if and returns revisited (not asking about multiple returns ok or not)
With regards this example from Code Complete: Comparison Compare(int value1, int value2) { if ( value1 < value2 ) return Comparison_LessThan; else if ( value1 > value2 ) return Comparison_GreaterThan; else return Comparison_Equal; } You could also write this as: Comparison Compare(int value1, int value2) { if ( va...
Readability aside, the compiler should be smart enough to generate identical code for both cases.
1,099,334
1,099,483
add custom context menu to hosted web browser control
I am hosting a web browser control, and want to provide my own context menu. Ideally, I want to present my own context menu, that contains the original browser's context menu (with all addins etc.) as a sub menu. If that's not possible / to tricky, I'd be ok with e.g. normally showing my context menu, and showing the o...
Yes, you do need to implement IDocHostUIHandler. Ok, i guess you could intercept right-clicks, keystrokes, and that other message that'll normally display a context menu... But that's probably gonna break badly sooner or later; at very least, i'd expect it to break accessibility. Once you've intercepted IDocHostUIHan...
1,099,379
1,099,536
How to create a global parameters object
Here's a common, simple task: Read configuration settings from a configuration file, save the settings (e.g. as a hash) in an object, access this object from various objects that need to access the configuration parameters. I found this implementation for the ConfigFile class implementation and it works. My question is...
If you're going to roll-your-own, I would recommend using the Singleton design pattern for your configuration class. Have the class itself store a static pointer of its own type, and the constructor be private so one would be forced to use the static getter to get the one instance of the class. so a mock-up (that may n...
1,099,427
1,190,933
Can one unroll a loop when working with an integer template parameter?
I have the following code: template <int size> inline uint hashfn( const char* pStr ) { uint result = *pStr; switch ( size ) { case 10: result *= 4; result += *pStr; case 9: result *= 4; result += *pStr; ... ... case 2: result *= 4; ...
I would tend to do it recursively with templates. E.g. : template<class TOp,int factor> struct recursive_unroll { __forceinline static void result( TOp& k ) { k(); recursive_unroll<TOp,factor-1>::result( k ); } }; template<class TOp> struct recursive_unroll<TOp,0> { __forceinline static voi...
1,099,436
1,099,461
Inheriting from std::exception, ambiguity in definitions of std::exception
So I am a little confused, I have been looking around trying to determine an appropriate way of inheriting from std::exception for my own type. Now according to cplusplus.com (and i know this isn't necessarily the standard, thats why I'm asking), std::exception is a base class with no members. However, after looking at...
The std::exception class is defined as: namespace std { class exception { public: exception() throw(); exception(const exception&) throw(); exception& operator=(const exception&) throw(); virtual ~exception() throw(); virtual const char* what() const throw(); ...
1,099,513
1,099,740
Threadsafe Vector class for C++
Does anyone know a quick and dirty threadsafe vector class for c++? I am multithreading some code, and I believe the problem I have is related to the way the vectors are used. I plan to rewrite the code, but before I go crazy redoing the code, I would like to test it with a threadsafe vector to be sure. I also figur...
This is difficult because of algorithms. Suppose you wrapped vector so that all its member functions are serialised using a mutex, like Java synchronized methods. Then concurrent calls to std::remove on that vector still wouldn't be safe, because they rely on looking at the vector and changing it based on what they see...
1,099,601
1,099,756
ifstream seekg beyond end does not return eof in VS 2008 Express?
In VS 2005, I have some code that looks like this: ifs.open("foo"); while (!ifs.eof()) { ifs.read(&bar,sizeof(bar)); loc = ifs.tellg(); loc += bar.dwHeaderSize; // four byte boundary padding if ((loc % 4) != 0) loc += 4 - (loc % 4); ifs.seekg(loc,ios::beg); } ifs.close(); The code worke...
The EOF flag is only triggered after you attempt to read past the end of file. Reading upto the end of file will not trigger it. This is why most code looks like this: while(ifs.read(&bar,sizeof(bar))) { // Do Stuff } If the result of the read() goes upto the EOF the loop will be entered. If the result of the re...
1,099,717
1,099,803
C++ Encapsulation Techniques
I'm trying to properly encapsulate a class A, which should only be operated on by class B. However, I want to inherit from class B. Having A friend B doesn't work -- friendship isn't inherited. What's the generally accepted way of accomplish what I want, or am I making a mistake? To give you a bit more color, class A r...
I assume you want to allow descendants of B to access A directly? If A and B are tightly coupled, you can make A a protected class definition within B itself, instead of being an independent definition. E.G. class B { protected: class A { }; }; Another idea is to create protected methods on B that delegat...
1,100,432
1,100,524
Performance impact of using write() instead of send() when writing to a socket
I am working on writing a network application in C++ on the Linux platform using the typical sockets API, and I am looking at 2 alternative ways of writing a byte array to a TCP stream: either by calling write(), or by calling send(). I know that, since this is Linux, the socket handle is simply a file descriptor, and...
There should be no difference. Quoting from man 2 send: The only difference between send() and write() is the presence of flags. With zero flags parameter, send() is equivalent to write(). So long as you don't want to specify and flags for send() you can use write() freely.
1,100,561
1,100,606
"stable_sort()ing" a STL <list> in C++
I think the question title is clear enough: is is possible to stable_sort() a std::list in C++? Or do I have to convert it to a std::vector? I'm asking because I tried a simple example and it seems to require RandomAccessIterators, which a linked list doesn't have. So, how do I stable sort a std::list()? EDIT: sample c...
std::list::sort is already stable. From the standard, section 23.2.24: "Notes: Stable: the relative order of the equivalent elements is preserved."
1,100,671
1,100,738
Error in std::list::sort with custom comparator (expected primary-expression before ')' token)
The title is the main question. The exact scenario (I am 'using namespace std;'): void SubstringMiner::sortByOccurrence(list<Substring *> & substring_list) { list::sort(substring_list.begin(), substring_list.end(), Substring::OccurrenceComparator); } This is the comparator definition: class Substring { // ... ...
list member sort is a non-static function so must be called on a list instance. substring_list.sort( Substring::OccurrenceComparator() ); Edit: You can't use the free function std::sort as it requires random access iterators which list iterators are not.
1,100,917
1,101,161
iPhone OpenGL ES incorrect alpha blending
I have a problem with incorrect alpha blending results with openGL ES on iPhone. This is my code for creating texture object: glGenTextures(1, &tex_name); glBindTexture(GL_TEXTURE_2D, tex_name); glTextImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, GL_RGBA, GL_UNSIGNED_BYTE, tex_data); 'tex_data' is loaded f...
Found the problem. I've forgot to set opaque property of CAEAGLLayer of EAGLView to YES.
1,101,028
1,101,639
Display 32bit bitmap - Palette
I have an image data in a buffer(type - long) from a scanner which is 32 bit. For example, buffer[0]'s corresponding pixel value is 952 which is [184, 3, 0, 0] <-[R,G,B,A]; I want to display/Paint/draw on to the screen; I am confused when i tried to read about displying bitmaps. I looked at win32 functions, CBitmap cl...
Here's a simplified approach you can try, broken down into steps: BITMAPINFO bitmapinfo = { 0 }; bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapinfo.bmiHeader.biWidth = 1004; bitmapinfo.bmiHeader.biHeight = -1002; bitmapinfo.bmiHeader.biPlanes = 1; bitmapinfo.bmiHeader.biCompression = BI_RGB; HBITMAP hB...
1,101,135
1,101,156
writing list of dynamic array to file in binary form>
I want to write a structure which has a list of integer id. The list can be of varying length. typedef struct ss_iidx_node { int totalFreq; vector < int > docIDList; }s_iidx_node; Now, I wish to write this structure in a file and read it back. How can I do it? Wrting is done: fwrite(&obj,sizeof(s_iidx_node)...
Though I'd rather see an approach based on an explicit serialisation, you could try: fwrite(&obj.totalFreq,sizeof(int),1,dat_fd2); fwrite(&obj.docIDList[0],sizeof(int),obj.totalFreq,dat_fd2); Assuming totalFreq == docIDList.size(), it's a spurious variable, so a better implementation would be: size_t size=obj.docIDLis...
1,101,239
1,101,562
Is it possible to customize the Visual Studio autoformat?
I'm using Visual Studio to develop a C/C++ library. I would like to know if there is a way to customize the autoformat tool (Ctrl+K,F) so that: It automatically break lines that are bigger than 120 columns Format a function/method parameter the following way: void myFunction(int parameterA, float parameterB, ...
If those options are not good enough for you get UniversalIndentGUI it is a frontend for a whole slew of code formatting engines, you should be able to get the style that you want from it
1,101,599
1,101,650
Good C++ string manipulation library
I'm sorry for flaming std::string and std::wstring. They are quite limited and far from being thread safe. Performance wise, they are not that good too. I miss simple features: Splitting a string into array/vector/list Simple & intuitive case-insensitive find & replace Support for i18n without worrying about string o...
The C++ String Algorithms Library from Boost has pretty much all of the features you need.
1,101,876
1,102,093
Best Data Structure for Genetic Algorithm in C++?
i need to implement a genetic algorithm customized for my problem (college project), and the first version had it coded as an matrix of short ( bits per chromosome x size of population). That was a bad design, since i am declaring a short but only using the "0" and "1" values... but it was just a prototype and it worke...
I'm guessing you want random access to the population and to the genes. You say performance is important, which I interpret as execution speed. So you're probably best off using a vector<> for the chromosomes and a vector<char> for the genes. The reason for vector<char> is that bitset<> and vector<bool> are optimize...
1,102,007
4,456,422
Broken std::map visualiser in VS2005
I'm using the Intel compiler and visual studio and I can't seem to debug values that are in maps. I get a quick preview which shows the size of the map but the elements only show up as "(error)", I'll illustrate with a quick example, i've generated a map with a single entry myMapVariable[6]=1; if I mouse over I get thi...
I have never been able to fix this problem using Intel, but I have now moved to the latest visual studio compiler VS2010 and this is no longer a problem. I'm marking this as the answer because I don't want to leave unanswered questions lying around.
1,102,156
1,106,542
Handling binary dependencies across platforms
I've got a C++ project where we have loads and loads of dependencies. The project should work on Linux and Windows, so we've ported it to CMake. Most dependencies are now included right into the source tree and build alongside the project, so there are no problems with those. However, we have one binary which depends o...
If the binary is independant of the other part of your build process, you definitively should check-in it. But as you cannot include every version of the binary (I mean for every platform and compile flags the user might use) the build from source seems mandatory. I have done something similar. I have checked-in the so...
1,102,507
1,102,559
What does a "true;" or "10;" statement mean in C++ and how can it be used?
In C++ one can write any of the following statements: 10; true; someConstant; //if this is really an integer constant or something like int result = obtainResult(); result; // looks totally useless The latter can be used to suppress a compiler warning "A variable is initialized but not referenced" (C4189 in VC++) if ...
These statements (called expression-statements in the C++ grammar) are valid because they are expressions. Expressions are all constructs that calculate some kind of value, such as 3 + 5 someVariable someFunctionCall( 2 ) someVar += 62 val > 53 I think, to keep the grammar simple, they decided to not differentiate be...
1,102,853
1,103,171
Handling different datatypes in a single structure
I need to send some information on a VxWorks message queue. The information to be sent is decided at runtime and may be of different data types. I am using a structure for this - struct structData { char m_chType; // variable to indicate the data type - long, float or string long m_lData; // variable to hol...
There are many ways to handle different datatypes. Besides the union solution you can use a generic struct like : typedef struct { char m_type; void* m_data; } structData; This way you know the type and you can cast the void* pointer into the right type. This is like the union solution a more C than C++ way o...
1,102,918
1,386,020
Windows not drawing above OpenGL windows
I have an application with an OpenGL window as a child window of the main window. When I display a dialog box above the OpenGL window, it doesn't get drawn. It's like it's not getting WM_PAINT messages. If I can guess the title bar position of the dialog box, I can drag it and it's still responsive. I realise this mig...
Bugger. Should have given all the details. I was running Windows in a virtual machine on Mac OS X using Parallels. I upgrade from Parallels 3 to 4 and now everything is working fine. I suspect a Parallels video driver issue. Thanks to all those who answered with suggestions.
1,103,047
1,105,009
Capturing syscall stdout without writing to file in C/C++
I want to read the std output of a system call into a C/C++ string. Can I do this without using a temp file? Perl //without file io $output = `echo hello`; C++ //with file io system ("echo hello > tmp"); std::fstream file ("tmp"); std::string s; file >> s;
Using C's popen (probably the simplest solution, even if it doesn't use C++'s iostream): FILE *p = popen("echo hello", "r"); std::string s; for (size_t count; (count = fread(buf, 1, sizeof(buf), p));) s += string(buf, buf + count); pclose(p); Assuming your iostream has the non-standard xfstream::xfstream(int fd) c...
1,103,313
1,103,342
Is anybody using the named boolean operators?
Or are we all sticking to our taught "&&, ||, !" way? Any thoughts in why we should use one or the other? I'm just wondering because several answers state thate code should be as natural as possible, but I haven't seen a lot of code with "and, or, not" while this is more natural.
Those were not supported in the old days. And even now you need to give a special switch to some compilers to enable these keywords. That's probably because old code base may have had some functions || variables named "and" "or" "not".
1,103,385
1,103,832
is it safe to recv passing in 0 to detect a socket error?
For a TCP blocking socket, is it safe to call: if(SOCKET_ERROR != recv(s, NULL, 0, 0)) //... to detect errors? I thought it was safe, then I had a situation on a computer that it was hanging on this statement. (was with an ssl socket if that matters). I also tried passing in the MSG_PEEK flag with a buffer specifie...
In addition to other answers - here's a handy little function to get the pending socket error: /* Retrives pending socket error. */ int get_socket_error( int sockfd ) { int error; socklen_t len( sizeof( error )); if ( getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ) < 0 ) error = errno; ...
1,103,863
1,151,491
Painting on top of video in a Qt Widget
I am developing a Qt application that can play the videos and shows some scrolling bar along the way. The window size MUST Not exceed the limit of 720px in height and 1280 in width. I use MPlayer as a slave process and pass it the winId() of the QWidget and it renders the video in it. Now I want another widget on top o...
When using MPlayer in this manner, I believe your best option would be to create a second window. There's a couple ways you could go from here, the fancier way which might not work on some versions/configurations of Xorg is to have the second window the same size as the first, and place it directly on top of the other...
1,103,933
1,103,988
Prompt with editable default in c++?
Is is possible (without external library such as boost) to prompt for input from the user, like using cin, but with a default choice that is editable by the user (without a GUI)? For example, the program will say: Give your input: default and the user can press enter to use "default" or press 1 then enter to get "def...
You may want to use GNU readline.
1,104,035
1,104,048
"Generic" iterator in c++
I have: void add_all_msgs(std::deque<Message>::iterator &iter); How can I make that function "generic", so it can take any kind of inputiterators ? I don't really care if it's iterating a deque,a vector or something else, as long as the iterator is iterating Message's. - is this at all straight forward possible in c++...
template<class InputIterator> void add_all_msgs(InputIterator iter); Usage: std::deque<Message> deq; add_all_msgs(deq.begin());
1,104,235
1,105,960
Is there a simpler Windows C++ Subversion API or an example .vcproj for minimal_client.c?
Following on the tails of my previous (answered) question... SharpSvn makes calling the Subversion client API simple: SvnClient client = new SvnClient(); client.Authentication.DefaultCredentials = new NetworkCredential(username, password); client.CheckOut(new Uri("http://xxx.yyy.zzz.aaa/svn/repository"), workingCopyDir...
It seems that C++ wrappers are not overflowing the 'net. However, you may want to try SVNCPP, which can be yoinked from RapidSVN. See http://rapidsvn.tigris.org/ for details (note: I've not tried it).
1,104,605
1,104,635
Need help with STL sort algorithm
I'm having some troubles with using the std::sort algorithm here. I was reading that you can just overload the less than operator to sort classes, but I have been getting all sorts of errors. I have also tried using a functor as you can see in the example I made below. I was hoping somebody could see what I'm doing wro...
I believe you need to change bool operator()(Thing& start, Thing& end) { into bool operator()(const Thing& start, const Thing& end) { and int val() { into int val() const { IOW, your code needs to be const-correct and not claim it may modify things it in fact doesn't (nor needs to).
1,104,816
1,105,151
Using templated "super"
Related question: Using "super" in C++ I examined the source code for OpenSteer and found the following code for defining properties of vehicles. The requirement is Super have too be inherited from an interface class AbstractVehicle. template <class Super> class SteerLibraryMixin : public Super { ... } template <class...
I think that doing: this->GetMaxSpeed() will solve your problem. Also You could do: SimpleVehicle::GetMaxSpeed() both of these explicitly say where the function is coming from.
1,105,058
1,105,074
Can I create an object from a derived class by constructing the base object with a parameter?
In other words, given a base class shape and a derived class rectangle: class shape { public: enum shapeType {LINE, RECTANGLE}; shape(shapeType type); shape(const shape &shp); } class rectangle : public shape { public: rectangle(); rectangle(const rectangle &rec); } I'd like to know if I could create an ins...
Short Answer: No Long Answer: You need a factory object/method. You can add a static factory method to the base class the creates the appropriate object type. class Shape { static Shape* createShape(shapeType type) { switch (type) { case RECTANGLE:return new rectangle(); ...
1,105,349
1,106,120
C++ OpenGL Window and Context creation framework / library
I'm searching for an multi platform OpenGL framework that abstracts the creation of windows and gl contexts in C++. I'd like to have an OO representation of Window, Context & co where i can instantiate a Window, create a Context and maybe later set the window to fullscreen. I'm thinking about implementing this myself f...
SMFL is another, similar to SDL, but takes a more object oriented approach.
1,105,398
1,109,834
Multiple Rendertargets in DX9
I've set m_lpD3DDevice->SetRenderTarget(0,Buffer1); m_lpD3DDevice->SetRenderTarget(1,Buffer2); m_lpD3DDevice->SetRenderTarget(2,Buffer2); and if I render the pixelshader only affects the first render target. It's output structure is struct PS_OUTPUT { float4 Color0 : COLOR0; float4 Color1 : COLOR1; ...
I finally have the answer now. All I had to do was to set ColorWriteEnable = red | green | blue; in the effect file. Everything else was correct. But I don't know why this made it work.
1,105,642
1,106,130
Adding SSL support to existing TCP & UDP code?
Here's my question. Right now I have a Linux server application (written using C++ - gcc) that communicates with a Windows C++ client application (Visual Studio 9, Qt 4.5.) What is the very easiest way to add SSL support to both sides in order to secure the communication, without completely gutting the existing protoc...
SSL is very complex, so you're going to want to use a library. There are several options, such as Keyczar, Botan, cryptlib, etc. Each and every one of those libraries (or the libraries suggested by others, such as Boost.Asio or OpenSSL) will have sample code for this. Answering your second question (how to integrate ...
1,105,839
1,105,862
MFC: GetWindowRect usage
I'm trying to determine the window position of an application. I know SetWindowPos() would set the window position at a certain position with a specific sizing. I would like to retrieve this information, but I have noticed some negative values in there. When I save these values into the registry and then load them on t...
You should be calling the GetWindowPlacement method to get the WINDOWPLACEMENT structure which has not only the window position, but the state of the window (minimized, maximized, etc, etc). In turn, you should store this information in the registry in addition to the position values and set the state of the window whe...
1,106,065
1,107,044
XPath support in Xerces-C
I am supporting a legacy C++ application which uses Xerces-C for XML parsing. I've been spoiled by .Net and am used to using XPath to select nodes from a DOM tree. Is there any way to get access some limited XPath functionality in Xerces-C? I'm looking for something like selectNodes("/for/bar/baz"). I could do this ...
See the xerces faq. http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9 Does Xerces-C++ support XPath? No.Xerces-C++ 2.8.0 and Xerces-C++ 3.0.1 only have partial XPath implementation for the purposes of handling Schema identity constraints. For full XPath support, you can refer Apache Xalan C++ or other Open Sour...
1,106,082
1,122,851
Open source project for c++ developer?
I am a vc++ developer (but like Qt) interested in learning from open source project by contributing and reading the code. I use windows as primary development platform. Which project will be right for me to start? Is chromium a good choice?
Is chromium a good choice? I believe so, yes! The source code is IMO very well written, it's a really active project with a lot of work to do and is also interesting in many different ways. Obviously a browser is in itself just a combination of specific libraries, and thus Chromium gives you a nice entry to learn mor...
1,106,149
1,106,167
What is a "translation unit" in C++?
I am reading at the time the "Effective C++" written by Scott Meyers and came across the term "translation unit". Could somebody please give me an explanation of: What exactly it is? When should I consider using it while programming with C++? Is it related to C++ only, or it can be used with other programming langua...
From here: (wayback machine link) According to standard C++ (wayback machine link) : A translation unit is the basic unit of compilation in C++. It consists of the contents of a single source file, plus the contents of any header files directly or indirectly included by it, minus those lines that were ign...
1,106,483
1,106,572
Modify a Binary file(an after effect project file) in c# or c++
I need to change some text values inside an after effect project file that I assume it's a binary file. You cannot edit this file with a text editor, if you do next time you open it you will encounter the error message about corrupted project file. So i need to for example change "TextArea1" to "Some new text" so as yo...
Have you got visual studio? If so, do: File->Open and select the file. On the open button, press the drop down arrow. Choose "Open With..." Select: Binary Editor. At least you can see what's in the file. This is at least a good starting point. It will show you the byte values, and any character value for the byte o...
1,106,519
1,106,602
Overwriting function in another dll without edits to primary dll
This one game I do scripting for uses a primary dll in which our scripts we write (creatively named "scripts.dll" This scripts.dll, server-side, loads other plugins (.dlls as well). Question: I need to override an existing function in scripts.dll in, for example, pluginA.dll to where the one in scripts.dll doesn't get ...
First I would try to adjust the caller to get this specific function pointer from pluginA.dll, and not from scripts.dll, through GetProcAddress. If that is not feasible, I would overwrite the start of the old function with a jump instruction to the new function. The jump instruction on x86 is "E9 XX XX XX XX"; notice t...
1,106,659
1,145,554
Handle HTMLElementEvents2 when DWebBrowserEvents2 has been handled using ATL's macros
I'm creating a Browser Helper Object using VS2008, C++. My class has been derived from IDispEventImpl among many others class ATL_NO_VTABLE CHelloWorldBHO : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CHelloWorldBHO, &CLSID_HelloWorldBHO>, public IObjectWithSiteImpl<CHelloWorldBHO>, ...
There is no real need to override Invoke or get IConnectionPointContainer. Since this is an ATL project, Implementing another IDispEventImpl: public IDispEventImpl<2, CHelloWorldBHO, &DIID_HTMLTextContainerEvents2, &LIBID_MSHTML, 4, 0> does the trick. Then, sink the entry as: SINK_ENTRY_EX(2, DIID_HTMLTextContainerEve...
1,106,820
1,106,838
Get Keyboard input c++ outside of terminal
I am trying to write a c++ program that responds to keyboard input. I want to run this as a daemon so I can't use cin, I would also like to output each character as it is pressed to a picoLCD screen that I have set up. What is the best way to do this?
If the application is running in the background as a daemon, you can use the common Windows approach of a "keyboard hook". This is performed much differently on Linux though and there are various methods you may want to look into. It is discussed a bit in this SO question: system wide keyboard hook on X under linux
1,106,930
1,107,432
Cygwin GDB gives error 193 when trying to start program
When I attempt to debug a simple program with gdb on cygwin I get the following: C:\Users\Benoit St-Pierre\workspace_cpp\cs454>gdb a.exe GNU gdb 6.8.0.20080328-cvs (cygwin-special) Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is fre...
The problem is that you have space character in your path name. Move the file to a different directory and gdb will be able to start the process.
1,107,149
1,107,235
Is it possible to get the value type from an arbitrary iterator (C++)?
I have a class template <typename Iterator, typename Value> class Foo { public: Foo(const Iterator& it) { ... } ... private: map<Value, int> m_; } }; Is there any way to get rid of Value in the template? The Iterator may or may not be an STL iterator, but it's guaranteed that *it type is Value. I know about...
Any iterator should provide iterator_traits<Iterator>::value_type. If it does not, then it is not an iterator. ISO C++ 2003 24.3.1[lib.iterator.traits] "Iterator traits": To implement algorithms only in terms of iterators, it is often necessary to determine the value and difference types that correspond to a par...
1,107,596
1,107,639
Trying to return multiple values
I'm having some trouble returning multiple values in this program that calculates min, max, mean, median. The first thing I did was pass reference arguments, and it worked - but I read that creating a struct or class is the preferred method to returning multiple values. So I tried and I haven't been able to get good re...
There are three ways to do it. 1) Return a maxv instance from the calculate function maxv calculate(vector<int>& max) { maxv rc; //return code ... some calculations ... ... initialize the instance which we are about to return ... rc.min_value = something; rc.max_value = something else; ... retur...
1,107,672
1,107,687
How to gain Access to member variables of a class using void pointer but Not Object
I am trying to access member variables of a class without using object. please let me know how to go about. class TestMem { int a; int b; public: TestMem(){} void TestMem1() { a = 10; b = 20; } }; void (TestMem::*pMem)(); int main(int argc, char* argv[]) { TestMem o1; ...
The "right" way to do this is by using the offsetof() macro from <stddef.h>. Unfortunately offsetof() has some fairly draconian restrictions in C++: Because of the extended functionality of structs in C++, in this language, the use of offsetof is restricted to "POD [plain old data] types", which for classes, more or l...
1,107,705
1,107,717
system("pause"); - Why is it wrong?
Here's a question that I don't quite understand: The command, system("pause"); is taught to new programmers as a way to pause a program and wait for a keyboard input to continue. However, it seems to be frowned on by many veteran programmers as something that should not be done in varying degrees. Some people say it is...
It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his n...
1,107,784
1,107,837
I'm trying to return a SDL Mix_Music data type, but I'm having problems
I know I could just make all the Mix_Musics public, and not worry about the problem, but I'd still like to understand how to do it. //header.h class Music { private: Mix_Music * BGMusic, * fall, * reset, * teleport, * win, * singleCubeWin; public: Music(); ...
From your code above I'm not absolutely certain what you are trying to do. The function 'getSound' takes a Mix_Music object as the parameter and returns the same object. Now from some deduction I assume that you are trying to request the BGMusic object via a string. There a few ways to do this, via IDs for each of Mix_...
1,107,846
1,107,900
Display c++ code in php
I am trying to display the contents of a .cpp file in php. I am loading it using fread when I print it out it comes out formatted incorrectly. How can I keep the format without escaping each character?
<?php echo "<pre><code>"; $filename = "./test.cpp"; $handle = fopen($filename, "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096); // assuming max line len is 4096. echo htmlspecialchars($buffer); } fclose($handle); } echo "</code></pre>"; ?> We need htmlspecial...
1,107,862
1,107,895
HTTP client example on win32
I wanted to develop one HTTP example on win32 platform, which is asynchronous. I am new to win32 programming, what are the api and library win32 platform provides for HTTP send and receive request? I am using Windows XP with VS 2005. If any example is available please provide a link to it.
You can use WinHTTP library. Here is an sample on Asynchronous completion.
1,107,940
1,108,181
size_t can not be found by g++-4.1 or others on Ubuntu 8.1
This has happened before to me, but I can't remember how I fixed it. I can't compile some programs here on a new Ubuntu install... Something is awry with my headers. I have tried g++-4.1 and 4.3 to no avail. g++ -g -frepo -DIZ_LINUX -I/usr/include/linux -I/usr/include -I/include -c qlisttest.cpp /usr/include/libio.h:...
Start by removing -I/usr/include/linux and -I/usr/include. Adding system directories to include paths manually either has no effect, or breaks things. Also, remove -frepo for extra safety.
1,107,948
1,108,097
Test whether a class is polymorphic
We have a sub-project 'commonUtils' that has many generic code-snippets used across the parent project. One such interesting stuff i saw was :- /********************************************************************* If T is polymorphic, the compiler is required to evaluate the typeid stuff at runtime, and answer will b...
I cannot imagine any possible way how that typeid could be used to check that type is polymorphic. It cannot even be used to assert that it is, since typeid will work on any type. Boost has an implementation here. As for why it might be necessary -- one case I know is the Boost.Serialization library. If you are saving ...
1,107,990
1,108,006
Scope, arrays, and the heap
So, I have this array. It needs to be accessed outside the scope of this function. I have been slapping a pointer to it into a pair which gets put into a deque. But once I'm outside the scope, the local stack is gone, the array is invalid, and I've just got a useless pointer, right? So I've trying to put this array ont...
The whole concept looks strange to me. If you declare array on the stack, it will not exist outside the scope of your function. If you allocate it using 'new' - make sure you 'delete' it sometime, otherwise it's memory leak! The correct code with 'new' is: int *blah = new int[4]; ... // don't forget to: delete [] blah;...
1,108,029
1,108,037
How i am able to use string without #include<string>?
It is given in the STL reference that string class is in string header,then without including the header how the following program is running without an error?? #include<iostream> using namespace std; int main() { string s; cin>>s; cout<<"string entered is : "<<s; } I am using a g++ complier on ubuntu machine....
Perhaps because iostream itself includes string in that compiler's implementation of the libraries. But this is not the case in other library implementations, e.g. Microsoft's VC++ doesn't allow this. You shouldn't rely on that kind of implicit inclusion, as it varies from compiler to compiler, and even from version to...
1,108,105
1,108,118
Condition order in while loop
First of all, before I begin, I am using VC++ 2008 professional, running an Intel core2 on windows OS. I also know that this code will NEVER be executed on anything other than a core2/corei7 running Windows. I have a while loop with 2 conditions that looks something like this: note: this is a much simplified version. w...
The second condition will not be evaluated unless the first one has been evaluated to true. You can count on this. Millions lines of code work because this is how C and C++ do short-curcuit logical expressions evaluation. You can use it and count on it. If the first expression evaluates to false the second will not eve...
1,108,203
1,109,021
I18n C++ hello world with plurals
Complete C++ i18n gettext() “hello world” example has C++ code that works for a simple fixed string. I am now looking for an example program that works with plurals. This example code displays six lines. Only one is correct in English. It does not handle the plurals correctly. cat >helloplurals.cxx <<EOF // hellopurals...
I'm not sure what you want. If it is slight modification of your example that give your wanted output, just replace the printf line by printf(ngettext("Hello world with %d moon\n", "Hello world with %d moons\n", ii), ii); but as it is a trivial modification of unwind's answer and the gettext documentation has the ver...
1,108,273
1,108,297
Is there a better way to pass command line arguments to my programs in VC++?
I'm writing a program in C++ and it takes some command line arguments. The only way I know to pass command line arguments in VSC++ is to open up the properties and navigate to the command line argument field and enter them in, then run it. That's not exactly streamlined if I want to pass in different arguments each tim...
If its just for quick testing or whatever, you could just create local variables in your main method instead of passing arguments in. Makes it a lot quicker/easier to change them.
1,108,360
1,108,525
delete a NULL pointer does not call overloaded delete when destructor is written
class Widget { public: Widget() { cout<<"~Widget()"<<endl; } ~Widget() { cout<<"~Widget()"<<endl; } void* operator new(size_t sz) throw(bad_alloc) { cout<<"operator new"<<endl; throw bad_alloc(); } void operator delete(void *v) { ...
I remember something similar on operator delete a while ago in comp.lang.c++.moderated. I cannot find it now, but the answer stated something like this .. Unfortunately, the language specification is not sufficiently clear on whether the control should go into the overloaded 'operator delete' when the delete-e...
1,108,537
1,108,557
How to import a tlb and a namespace in c++ at runtime when some condition meets?
Generally we import a tlb file at the starting of the program like #include < stdio.h > #import " sql.tlb " But i need to import a tlb file when certain condition meets in the middle of the program how can i do this. to load dll there is LoadLibrary() but to load tlb can i use LoadLibrary(). Since tlb is generated b...
You can load a type library at runtime using LoadTypeLib. ITypeLib *ptlib; LoadTypeLib("sql.tlb", &ptlib); What you do then with ptlib is kind of up in the air as you don't really say what you are trying to do with it. ptlib is an object supporting the ITypeLib interface. It has methods which you can call to enumerate...
1,108,682
1,108,738
type traits specialization
template<typename T> class vec3 { public: typename T type_t; T x; T y; T z; }; template<typename T> struct numeric_type_traits_basic_c { typedef T type_t; typedef T scalar_t; }; template<typename T> struct numeric_type_traits_vec3_c { typedef T type_t; typedef typename T::type_t scalar...
This is the syntax for partial class template specialisation: template<typename T> struct numeric_type_traits // basic template { typedef T type_t; typedef T scalar_t; }; template<typename T> struct numeric_type_traits< vec3<T> > // partial specialisation for vec3's { typedef vec3<T> type_t; typedef T ...
1,108,709
1,109,070
Solve boost.thread compilation error with Metrowerks compiler
I'm trying to use boost.thread with metrowerks codewarrior 5.5.3; in the header thread.hpp, I get the error that he's redefining thread::thread_data: class BOOST_THREAD_DECL thread { private: ... template<typename F> struct thread_data: detail::thread_data_base { F f; th...
The second instance is a partial specialization of the template class, this is valid C++ and should not result in a redefinition error. I've had problems with such features in a metrowerks compilers in the past too though, more specifically, when using template template parameters with default values, the compiler woul...
1,109,446
1,109,457
C++: generate gaussian distribution
I would like to know if in C++ standard libraries there is any gaussian distribution number generator, or if you have any code snippet to pass. Thanks in advance.
The standard library does not. Boost.Random does, however. I'd use that if I were you.
1,109,522
1,109,527
How to (fast) fill a CListCtrl in C++ (MFC)?
in my application I have a few CListCtrl tables. I fill/refresh them with data from an array with a for-loop. Inside the loop I have to make some adjustments on how I display the values so data binding in any way is not possible at all. The real problem is the time it takes to fill the table since it is redrawn row by ...
Look into the method SetRedraw. Call SetRedraw(FALSE) before starting to fill the control, SetRedraw(TRUE) when finished. I would also recommend using RAII for this: class CFreezeRedraw { public: CFreezeRedraw(CWnd & wnd) : m_Wnd(wnd) { m_Wnd.SetRedraw(FALSE); } ~CFreezeRedraw() { m_Wnd.SetRedraw(TRUE); } privat...
1,109,564
1,109,590
Intercept windows open file
I'm trying to make a small program that could intercept the open process of a file. The purpose is when an user double-click on a file in a given folder, windows would inform to the software, then it process that petition and return windows the data of the file. Maybe there would be another solution like monitoring Ope...
The best way to do it to cover all cases of opening from any program would be via a file system filter driver. This may be too complex for your needs though.
1,109,602
1,110,474
Using Protocol Buffers to send icons/small images
I have a simple question about std::string and google's protocol buffers library. I have defined a message like so: message Source { required string Name = 1; required uint32 Id = 2; optional string ImplementationDLL = 3; optional bytes Icon = 4; } I want to use the Icon field to send an image, it mos...
the answer to this question: How do you construct a std::string with an embedded null?
1,109,833
1,110,131
Accessing Function Variable After calling it while Being in main()
I want to access variable v1 & v2 in Func() while being in main() int main(void) { Func(); int k = ? //How to access variable 'v1' which is in Func() int j = ? //How to access variable 'v2' which is in Func() } void Func() { int v1 = 10; int v2 = 20; } I have heard that we can access from Stack. Bu...
You're in C/C++ land. There are little you cannot do. If this your own code, you shouldn't even try to do that. Like others suggested: pass a output parameter by reference (or by pointer in C) or return the values in a struct. However, since you asked the question, I assume you are attempting to look into something y...
1,109,995
1,110,101
Do getters and setters impact performance in C++/D/Java?
This is a rather old topic: Are setters and getters good or evil? My question here is: do compilers in C++ / D / Java inline the getters and setter? To which extent do the getters/setters impact performance (function call, stack frame) compared to a direct field access. Besides all the other reasons for using them, I w...
It depends. There is no universal answer that is always going to be true. In Java, the JIT compiler will probably inline it sooner or later. As far as I know, the JVM JIT compiler only optimizes heavily used code, so you could see the function call overhead initially, until the getter/setter has been called sufficientl...
1,110,125
1,110,172
Cost of passing an optional parameter to a method rather than computing it
I have a memory block that is divided into a series of location that can be retrieved and returned by client code. The method that returns locations back looks like this: void ReturnLocation(void *address) { int location = AddressToLocation(address); // I need the location here // some code DoSmthA(locatio...
Profile it. Do what is actually faster in your case, on your compiler and with your code base. Not what was faster in my unrelated test, on my unrelated compiler. Passing an argument to a function is a pretty cheap operation. A stack push/pop, basically. Computing the location might be very fast, if the division can b...
1,110,418
1,110,485
Do typedefs of templates preserve static initialization order?
Within the same compilation unit, the C++ standard says that static initialization order is well defined -- it's the order of the declarations of the static objects. But using the Sun Studio 12 compiler I'm encountering unintuitive behavior. I've define a templated class helper<T> which contains a static member _data o...
Within the same compilation unit, the C++ standard says that static initialization order is well defined -- it's the order of the declarations of the static objects. In your shown code you have no declaration of a static data member. You have a declaration of a typedef-name. These have nothing to do with that, and do...
1,110,458
1,110,549
WinForms interthread modification
Whenever I want to modify a winform from another thread, I need to use ->Invoke(delegate, params) so that the modification occurs in the winform's own thread. For every function that needs to modify the gui, I need another delegate function. Is there some scheme which allows me to limit the number of delegate functions...
If you're using C# 3, you can use lambda, and in C# 2, use anonymous delegates. These simplify the syntax when there's no need to reuse the behavior. One thing I always do is to do the synchronization in the form code, not in the controller. The controller shouldn't be bothered with these sort of "plumbing" problems...
1,110,658
1,110,692
Trying to keep age/name pairs matched after sorting
I'm writing a program where the user inputs names and then ages. The program then sorts the list alphabetically and outputs the pairs. However, I'm not sure how to keep the ages matched up with the names after sorting them alphabetically. All I've got so far is... Edit: Changed the code to this - #include "std_lib_faci...
Rather than two vectors (one for names, and one for ages), have a vector of a new type that contains both: struct Person { string name; double age; }; vector<Person> people; edit for comments: Keep in mind what you're now pushing onto the vector. You must push something of type Person. You can do this in a...
1,110,682
1,111,975
Extending PHP with C++?
I have a performance intensive routine that is written in PHP that I'd like to port to C++ for a performance increase. Is there any way to write a plugin or extension or something using C++ and interface with it from PHP? WITHOUT manually editing the actual PHP source?
I've written a PHP plugin in C++ with the help of SWIG. It's doable, but it may take a while to get used to the SWIG-compilation cycle. You can start with the SWIG docs for PHP. Update As @therefromhere has mentioned, I greatly recommend that you get the book Extending and Embedding PHP. There is almost no documentatio...
1,110,779
1,110,906
How C++ can import a DLL made in C#?
I have a DLL made in C#, this DLL contains some clases like Creator. I need to load this DLL and use Creator class in C++ unmanaged, so Is there some way to create that instance or must I load just the functions exposed? I need something like this: CreatorInstance->Init(); Is this posible?
John Fisher's approach using C++/CLI is by far the easiest means of handling this, but it is not the only means. The other three options are: 1) Use COM interop to wrap the .NET class via COM 2) You can host the CLR in your native, unmanaged application, and call into it. For details, see this article. 3) You can hos...
1,110,802
1,110,828
C++ Storing large data in std::list<> ..should I use reference counting?
How do people normally manage copying a list of large objects around? Here's my situation: Currently I have this: typedef std::vector<float> Image; and I'm storing it in a std::list<Image> lst; The Image.size() is quite large (each is ~3-5 MB). I'm passing (copying) the list around. Is it a correct understanding on...
Objects larger than built-in types are most often way cheaper to pass around by reference then by value. So if your object is about 3 Meg big, and you need to pass it around, please don't copy it! All STL types use value semantics: they copy their content. Note that content may exist of pointers. In that case the po...