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,377,685
1,377,707
virtual method not seen in implementation
i am currently working on a C++ project where i have an abstract interface that is implemented later on. The interface also has a implemented method which my implementation doesn't override. My problem is that when using my implementation, the compiler(MSVC) doesn't see the interface method. What causes this, and how c...
Name resolution happens before overload resolution. In impl.foo( name ), then compiler looks at the implementation class and finds only virtual A& foo(int i). It does not look at the base class as it has found a function with the right name. To correct this use can add a using interface::foo declaration to the derived ...
1,377,695
1,377,865
Is there a reason to use enum to define a single constant in C++ code?
The typical way to define an integer constant to use inside a function is: const int NumbeOfElements = 10; the same for using within a class: class Class { ... static const int NumberOfElements = 10; }; It can then be used as a fixed-size array bound which means it is known at compile time. Long ago compilers did...
The reason is mainly brevity. First of all, an enum can be anonymous: class foo { enum { bar = 1 }; }; This effectively introduces bar as an integral constant. Note that the above is shorter than static const int. Also, no-one could possibly write &bar if it's an enum member. If you do this: class foo { sta...
1,377,813
1,379,097
QT: reject() closing whole app? Why?
I'm running a QT app (VS2005) and have spawned a dialog from that app, but if I add a cancel button to that dialog with a reject() slot then yes, the dialog closes and returns the correct result but my whole app closes down as well. This is annoying me and I can't find any hint as to why; any suggestions gratefully re...
Perhaps look at setting this: http://doc.trolltech.com/4.5/qapplication.html#quitOnLastWindowClosed-prop to false? If that doesn't work, make sure you haven't got any signal / slot connections you may have forgotten about.
1,377,833
1,392,505
Unable to catch std::invalid_argument
I've run into an issue catching a std::invalid_argument exception that I'm not able to trace. I'm using gcc 4.4.0 (windows), pthreads-win32 2.8.0 the GC2 dll. Basically, from two threads (main thread and a thread started using pthread_create), I try to create an instance of class A at roughly the same time. The constr...
Posting final answer here in case someone looks for it in the future. The issue is a critical bug in gcc 4.4: http://n2.nabble.com/gcc-4-4-multi-threaded-exception-handling-thread-specifier-not-working-td3440749.html
1,377,843
1,386,069
Cannot get ::WideCharToMultiByte to work
I've got a DLL for injection. This is injected via CBT-hook. Now, when the desired process is encountered via CBT, I've detoured WinAPI's ExtTextOutW with my own. The specification of ExtTextOutW is: BOOL ExtTextOutW(HDC hdc, INT x, INT y, UINT...
Your code looks a little odd, does it compile? LocalAlloc should have two parameters and did you mean CP_ACP. Anyway instead I would: Ask WideCharToMultiByte for the correct size, just in case you change your code page in future. Check for > 0 (failure is represented by 0 and not -1) Use std strings just to make sure ...
1,377,852
1,377,911
Accessing functions in an ASM file from a C++ program?
Over here I asked about translating an ASM file to C, and from the responses it looked like there was no reasonable way to do it. Fine. So one of the responses suggested I just make use of the functions as-is and be done with it. Sounds good. But how? Holy crap I've tried everything I can think of! I'm using a Micr...
Looking at PIDInt.asm, it should be fairly straight-forward to call the functions from C/C++. First, you declare extern variables for everything listed in VARIABLE DEFINITIONS: extern unsigned char error0, error1; /* etc */ Then, you declare extern functions for all the things that have a "Function:" comment, taking n...
1,377,873
1,377,909
Eclipse CDT: Shortcut to switch between .h and .cpp?
In Eclipse, is there a keyboard shortcut for switching the editor view from viewing a .cpp file to a corresponding .h file, and vice versa?
Ctrl+Tab is the default shortcut. You can change it in Window → Preferences → General → Keys: Toggle Source/Header
1,377,912
1,377,968
Conflict between a namespace and a define
I have this serious problem. I have an enumeration within 2 namespaces like this: namespace FANLib { namespace ERROR { enum TYPE { /// FSL error codes FSL_PARSER_FILE_IERROR,... and somewhere else in my code, I use it like this: FANLib::Log::internalLog(FSLParser::FILE_IERROR, file_ierror, true, ...
Generally, you should avoid using all-caps identifiers as they are used for macros. In this case, I'd rename the namespace. (As a side note, <windows.h> #defines other stuff like GetPrinter and indeed it gets annoying. I usually go with #undef then. It also helps to only include <windows.h> in .cpp files and make sure ...
1,378,136
1,378,152
Ensuring correct Double Pointer passing method at compile-time in C++
in the past we encountered various memory-leaks in our software. We found out that these happened mostly due to incorrect usage of our own "free"-Methods, which free Queue-Message-Data and the likes. The problem is, in our deepest tool-functions there are two methods to free up dynamically allocated memory, with the f...
Try templates: template <class T> void free (T *pData); template <class T> void free (T **ppData); This should give you an exact match on the argument type and, hence, the compiler should call the correct implementation. You can either replace your original void-pointer implementations of free with the templated versi...
1,378,165
1,378,416
A good way to implement useable Callbacks in C++
I have a custom Menu class written in C++. To seperate the code into easy-to-read functions I am using Callbacks. Since I don't want to use Singletons for the Host of the Menu I provide another parameter (target) which will be given to the callback as the first parameter (some kind of workaround for the missing "this" ...
Your approach requires the callback functions to either be free functions or static members of a class. It does not allow clients to use member functions as callbacks. One solution to this is to use boost::function as the type of the callback: typedef boost::function<void (MenuItem*)> callback_type; AddItem(const std::...
1,378,197
1,378,256
How to write strings as binaries to file?
This is a C++ question. I have a class that contains a string: class MyClass{ public: std::string s; }; And I have an array of MyClass objects: MyClass * array = MyClass[3]; Now I want to write the array as binaries into a file. I cannot use: Ofstream.write((char *)array, 3 * sizeof(MyClass)) because the size of MyC...
In C++ it is usually done using the BOOST serialization class Programmatically you could do something like this: Writing: std::ofstream ostream("myclass.bin",std::ios::binary); if (!ostream) return; // error! std::size_t array_size = 3; ostream.write(reinterpret_cast<char*>(&array_size),sizeof(std::size_t)); for(MyCla...
1,378,250
1,379,739
What error codes can occur with CopyFileEx?
I'm writing some C++ code that needs to call the CopyFileEx function. The documentation for CopyFileEx, like most other WIN32 functions, says: If the function fails, the return value is zero. To get extended error information, call GetLastError. Which is all well and good - however does anyone know where I can find a ...
Microsoft doesn't give a list of all error codes an API might return for the simple reason that the list may change over time and various implementations of Windows, installed drivers or simple oversight (APIs often return errors caused by other APIs called within the one you called). Sometimes the docs call out specif...
1,378,364
1,378,428
How do you output variable's declared as a double to a text file in C++
I am very new to C++ and I am wondering how you output/write variables declared as double to a txt file. I know about how to output strings using fstream but I cant figure out how to send anything else. I am starting to think that you can't send anything but strings to a text file is that correct? If so then how would ...
As your tagging suggests, you use file streams: std::ofstream ofs("/path/to/file.txt"); ofs << amtDueIn20; Depending on what you need the file for, you'll probably have to write more stuff (like whitespaces etc.) in order to get decent formatting. Edit due to rmagoteaux22's ongoing problems: This code #include <io...
1,378,520
1,378,682
Elevated process in Vista does not overwrite files
I'm trying to run elevated process, say, file_copier.exe, from another host process with ShellExecuteEx and lpVerb = "runas" on Vista. It shows UAC dialog and runs elevated, and copies files to "dangerous" folders, but it does not overwrite existing files (exe's). I've read here: http://www.codeproject.com/KB/vista-se...
You are talking about virtualization of file system. To tell Windows that your program are aware of Windows rules you should change your manifest file. Add to the manifest the following text: <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!--The ID below indicates applicat...
1,378,588
1,378,625
How can I use Enum::GetName in unmanaged C++
I am using managed extensions in VS 2008 I want to print the name of an en enum value This code used to be fine VS 2003 Enum::GetName(__typeof(COMMAND_CODES),__box(iTmp)) but now I get a comile error here is my enum typedef enum { /* Command codes */ UMPC_NULL = 0, } COMMAND_CODES Any clues ? ;
Can you use rtti typeid() and use the name() field? Edit: From comment: Enum::GetName(COMMAND_CODES::typeid,iTmp)
1,378,735
1,378,807
Problem with file stream/fstream in Xcode C++
Here is a simple program to output to a text file: #include <iostream> #include <fstream> using namespace std; int main() { double myNumber = 42.5; fstream outfile("test.txt", fstream::out); outfile << "The answer is almost " << myNumber << endl; outfile.close(); } All that ends up being wrote to my text file is, "T...
I'm not sure what the problem is. Is it that it's never executed or that it's writing to the wrong path. To shed light on this try include unistd.h and insert this snippet. char* s = getcwd(NULL, 256); printf("im running and pwd is: %s\n", s); Inside xcode hit CMD-SHIFT-R to open the console and see if it prints anyth...
1,378,867
1,379,311
Using find_if on std::vector<std::string> with bind2nd and string::compare
This may seem to be an academic question, but still I would be very interested in the answer: I have a vector of strings s in which I would like to find a given string findme. This can be done using something like find(s.begin(), s.end(), findme); My question is: There must be a way doing the same using find_if and th...
One option is to cast the member function pointer to suitable type. Another thing you are forgetting is that std::string::compare returns 0 for equal strings, so you'll also need to negate the functor. All in all: std::find_if( vec.begin(), vec.end(), std::not1( std::bind2nd( std::mem_fun_re...
1,379,246
1,379,261
Any reason to replace while(condition) with for(;condition;) in C++?
Looks like while( condition ) { //do stuff } is completely equivalent to for( ; condition; ) { //do stuff } Is there any reason to use the latter instead of the former?
There's no good reason as far as I know. You're intentionally misleading people by using a for-loop that doesn't increment anything. Update: Based on the OP's comment to the question, I can speculate on how you might see such a construct in real code. I've seen (and used) this before: lots::of::namespaces::container:...
1,379,533
1,379,541
How can I see symbols of (C and C++) binary on linux?
Which tools do you guys use? How do demangle c++ symbols do be able to pass it to profiler tools, such as opannotate? Thanks
Use nm to see all symbols and c++filt to demangle. Example: nm -an foo | c++filt
1,379,542
1,379,716
Qt-GUI with several "pages", how to synchronize the size of several QWidgets
I am currently writing a wizard-style application using Qt4. I am not using the wizard class however, since going next/back does not make sense from every step in the process. The user starts off at a "hub"-window with five buttons, each of which take him to another window at a different stage of the process. At the be...
Create one top-level widget that holds the others. I suggest that you either use QStackedWidget, or, if you want more control, create your own widget and use QStackedLayout directly.
1,379,564
1,380,733
C++: tiny memory leak with std::map
I am writing a custom textfile-data parser (JSON-like) and I have lost many hours trying to find a tiny memory leak in it. I am using VC++2008 and the commands _CrtMemCheckpoint and _CrtDumpMemoryLeaks to check for memory leaks. When I parse any file and then remove it from memory (alongside any other memory claimed), ...
The "{290}" in the leak report is the sequence number of the memory allocation for the memory block that was leaked. If this sequence number is always the same, you can use _crtBreakAlloc to cause a break in the debugger when that allocation sequence number is hit. From the stack trace you can find out where this blo...
1,379,735
1,379,778
visual studio - run several applications at once
The project, I work on, consists of several executables which run in background and a frontend. I develop in Visual Studio 2005. Often I need to run one background app with breakpoints enabled and then control it from the frontend. I set the important background app as a startup project and press F5. Then I start the f...
Visual Studio lets you start multiple projects when you hit F5. See How to: Set Multiple Startup Projects In a nutshell: In Solution Explorer, select the solution. On the Project menu, click Properties. The Solution Property Pages Dialog Box opens. Expand the Common Properties node, and click Startup Project. Click Mu...
1,379,770
1,416,170
How can I use std::for_each with boost::bimap?
I have a boost::bimap and I want to iterate over all positions to add the values of the given side to another STL-compatible container. How can I do this? My approach was to use std::for_each together with boost::bind: std::for_each(mybimap.left.begin(), mybimap.left.end(), boost::bind(&vect...
This should work: std::for_each(mybimap.left.begin(), mybimap.left.end(), boost::bind(&vector_type::push_back, &myvec, boost::bind(&map_type::left_map::value_type::second, _1))); ... or if you mean the key values mapped from instead of the values being mapped to, us...
1,379,932
1,380,025
trick question regarding declaration syntax in C++
Have a look here: In the following code, what would be the type of b? struct A { A (int i) {} }; struct B { B (A a) {} }; int main () { int i = 1; B b(A(i)); // what would be the type of b return 0; } I'll appreciate it if anybody could explain to me thoroughly why would such syntax exist :) Than...
One of C's warts (and C++ inherits it (and makes it worse)) is that there is no special syntax for introducing a declaration. This means declarations often look like executable code. Another example: A * a; Is this multiplying A by a, or is it declaring something? In order to make sense of this line you have to kno...
1,379,992
1,380,129
Qt doesn't find QStackedWidgets' slot setCurrentWidget
I am writing a wizard-style application in Qt that uses a QStackedWidget to organize the individual pages of the wizard. Now I want to switch between the pages, which should be possible using the function setCurrentWidget(...): I have a simple main class that instantiates a QWidget audioconfig. Then, it adds this QWidg...
QObject::connect(&hub, SIGNAL(configure()), &pageStack, SLOT(setCurrentWidget(&audioconfig))); When you connect a signal to a signal/slot, you connect a signature. The actual parameters are passed when emitting the signal. The above should probably be setCurrentWidget(QWidget*), but even so it won't work, because the...
1,380,135
1,380,364
Can you evaluate a constructor call to boolean with an overloaded bool()?
Can a constructor call be evaluated to a boolean if the bool() operator is overloaded? class A { public: A() {}; operator bool() const { return true; } } main() { if (A a = A()) { // do stuff } } Is the above code valid, or do I need to implement main like: int main(int argc, const char* argv[]) { A a()...
The code contains a few syntactic and semantic bugs. Let's fix them class A { public: A() {}; operator bool() { return true; } }; int main() { if (A a = A()) { // do stuff } } You may choose to change the type in the conversion function to something else. As written, the boolean conversion will also suc...
1,380,192
1,380,212
XML Serialization/Deserialization in C++
I am using C++ from Mingw, which is the windows version of GNC C++. What I want to do is: serialize C++ object into an XML file and deserialize object from XML file on the fly. I check TinyXML. It's pretty useful, and (please correct me if I misunderstand it) it basically add all the nodes during processing, and final...
I notice that each TiXmlBase Class has a Print method and also supports streaming to strings and streams. You could walk the new parts of the document in sequence and output those parts as they are added, maybe? Give it a try..... Tony
1,380,358
1,380,377
Calling timeconsuming functions from a constructor
What I'm looking right now is a set of classes derived from a common base class. Most, but not all, of the classes require some input parameters which are obtained through modal dialogs. Those dialogs are set up and executed in the constructor of the classes. As long as the dialog isn't finished, the object isn't const...
No "problems" can arise as far as the language is concerned. The constructor is allowed to take as long as it likes. Where it might be a problem is in the confusion it might cause. Will the programmer using the class be aware that the constructor blocks the thread for a long time? Without knowing any details of your c...
1,380,371
1,380,432
What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?
It seems that many projects slowly come upon a need to do matrix math, and fall into the trap of first building some vector classes and slowly adding in functionality until they get caught building a half-assed custom linear algebra library, and depending on it. I'd like to avoid that while not building in a dependenc...
There are quite a few projects that have settled on the Generic Graphics Toolkit for this. The GMTL in there is nice - it's quite small, very functional, and been used widely enough to be very reliable. OpenSG, VRJuggler, and other projects have all switched to using this instead of their own hand-rolled vertor/matr...
1,380,463
1,380,496
Sorting a vector of custom objects
How does one go about sorting a vector containing custom (i.e. user defined) objects. Probably, standard STL algorithm sort along with a predicate (a function or a function object) which would operate on one of the fields (as a key for sorting) in the custom object should be used. Am I on the right track?
A simple example using std::sort struct MyStruct { int key; std::string stringValue; MyStruct(int k, const std::string& s) : key(k), stringValue(s) {} }; struct less_than_key { inline bool operator() (const MyStruct& struct1, const MyStruct& struct2) { return (struct1.key < struct2.key); ...
1,380,567
1,380,602
Can I use an stl map if I plan to use arbitrary class objects as the key?
I'm new to STL. The thing stumping me about using a map to store arbitrary objects: std::map<MyClassObj, MyDataObject> MyMap; is how I find objects. How would MyMap.find (MyClassObjInstance) work for instance? Do I need to implement my own iterator and provide some standard functions which would include some equival...
std::map has a third template argument, after key and value, to denote what function is going to be used to compare keys. By default, it is std::less, which in it's turn uses operator<. So if your class has an operator<, it's ok, else you can provide a comparator of your own.
1,380,585
1,380,613
map of vectors in STL?
I want to have a map of vectors, (but I don't want to use pointer for the internal vector), is it possible? // define my map of vector map<int, vector<MyClass> > map; // insert an empty vector for key 10. # Compile Error map.insert(pair<int, vector<MyClass> >(10, vector<MyClass>)); I know that if I have used pointer...
The first data structure will work. You might want to typedef some of the code to make future work easier: typedef std::vector<MyClass> MyClassSet; typedef std::map<int, MyClassSet> MyClassSetMap; MyClassSetMap map; map.insert(MyClassSetMap::value_type(10, MyClassSet())); or (thanks quamrana): map[10] = MyClassS...
1,380,653
1,381,910
Why do you need to append an L or F after a value assigned to a C++ constant?
I have looked at quite a few places online and can't seem to find a good explanation as to why we should append an F or L after a value assigned to a C++ constant. For example: const long double MYCONSTANT = 3.0000000L; Can anyone explain why that is necessary? Doesn't the type declaration imply the value assigned to ...
Floating-point constants have type double by default in C++. Since a long double is more precise than a double, you may lose significant digits when long double constants are converted to double. To handle these constants, you need to use the L suffix to maintain long double precision. For example, long double x = 8.99...
1,380,829
1,380,926
Is extern "C" only required on the function declaration?
I wrote a C++ function that I need to call from a C program. To make it callable from C, I specified extern "C" on the function declaration. I then compiled the C++ code, but the compiler (Dignus Systems/C++) generated a mangled name for the function. So, it apparently did not honor the extern "C". To resolve this...
The 'extern "C"' should not be required on the function defintion as long as the declaration has it and is already seen in the compilation of the definition. The standard specifically states (7.5/5 Linkage specifications): A function can be declared without a linkage specification after an explicit linkage specificati...
1,380,907
1,380,932
Error calling function and passing a reference-to-pointer with a derived type
Can somebody explain why the following code is not valid? Is it because the offset for the variable named d is different than the variable named b? class Base { public: int foo; }; class Derived : public Base { public: int bar; }; int DoSomething( Base*& b ) { return b->foo; } Base* b = new Derived; Derived* d = new...
Imagine you could do that. The reference is not const, so it's possible for DoSomething to assign to the pointer and that will be visible in the caller. In particular, inside DoSomething it's possible for us to change the pointer to point to something that isn't an instance of Derived. If the caller then tries to do De...
1,381,078
1,381,368
Parallel reads from STL containers
It is safe to read a STL container from multiple parallel threads. However, the performance is terrible. Why? I create a small object that stores some data in a multiset. This makes the constructors fairly expensive ( about 5 usecs on my machine. ) I store hundreds of thousands of the small objects in a large multi...
You mentioned copy constructors. I assume that these also allocate memory from the heap? Allocating heap memory in multiple threads is a big mistake. The standard allocator is probably a single pool locked implementation. You need to either not use heap memory (stack allocate) or you need a thread optimized heap alloca...
1,381,627
1,381,696
Get a pointer to structure in a map C++
Ok so I have struct like this typedef struct { float x; float y; char name[]; } pTip; And another struc typdef struct { float xx; float yy; pTip *tip; }finalTip; I create and populate a map<string, pTip> maps That works fine. I am now trying to generate vector of finalTips I do: map<string, pTip>::const...
You want final.tip = &iter->second; Since iter is a map<string, pTip> iterator, iter->second is a reference to pTip. Take its address with & to get a pointer. Unfortunately, since you have a const_iterator, &iter->second will be a (const pTip *) So, either get a non-const iterator, or make the .tip member a const pTi...
1,381,646
1,381,802
How Do I use LoadLibrary in COM Accross Multiple Threads?
Let's say that I have the following code that's run in one thread of a multi-threaded COM application: // Thread 1 struct foo { int (*DoSomething)(void ** parm); }; HMODULE fooHandle = LoadLibrary("pathToFoo"); typedef int (*loadUpFooFP)(foo ** fooPtrPtr); loadUpFooFP loadUpFoo; loadUpFoo = (loadUpFooFP)GetProcAdd...
There's nothing COM related in the code you've shown. LoadLibrary is not thread-specific, so once you have the handle to the lib, you can reuse it from all your threads. Same applies to the pointer to the fooLoader method. However, there certainly could be something COM-specific inside fooLoader. Also, what's not clear...
1,381,757
1,381,801
Good multithreading guides?
I'm looking for a good guide/tutorial on multithreading in C++ (and ideally in general). Can anyone point me to a good online resource? EDIT: I intend to familiarize myself with either the boost threading library or the one from Poco.
The Dr. Dobbs article "The Boost.Threads Library" is a short introduction to the subject, using one of the Boost C++ Libraries.
1,381,798
1,385,051
function calling convention with boost::function_types
I've just been experimenting with the boost::function_types library recently, and I've come across a bit of a snag. I want to find out the calling convention of a given function, however I'm not quite sure how to do this. Here's what I have so far: This produces an error about how it cannot find the *_cc tag values in...
It seems like I was simply missing one of the header files (config/config.hpp) #define BOOST_FT_COMMON_X86_CCs 1 #include <boost/function_types/config/config.hpp> #include <boost/type_traits.hpp> #include <boost/function_types/property_tags.hpp> #include <boost/function_types/is_function.hpp> #include <boost/function_t...
1,381,937
1,381,946
SetJmp/LongJmp: Why is this throwing a segfault?
The following code summarizes the problem I have at the moment. My current execution flow is as follows and a I'm running in GCC 4.3. jmp_buf a_buf; jmp_buf b_buf; void b_helper() { printf("entering b_helper"); if(setjmp(b_buf) == 0) { printf("longjmping to a_buf"); longjmp(a_buf, 1); }...
You can only longjmp() back up the call stack. The call to longjmp(b_buf, 1) is where things start to go wrong, because the stack frame referenced by b_buf no longer exists after the longjmp(a_buf). From the documentation for longjmp: The longjmp() routines may not be called after the routine which called the setjmp()...
1,381,939
1,381,980
Taking iterators two at a time?
I'll often represent and process polylines like so: typedef std::vector< Point_t > Polyline_t; double PolylineLength(const Polyline_t& line) { double len = 0.0; for( size_t i = 0; i < line.size()-1; ++i ) len += (line[i+1]-line[i+0]).length(); return len; } The most straightforward conversion to b...
I would keep two iterators, and then check whether the second iterator has reached end. This will make it not require bidirectional iterators anymore: typedef std::list< Point_t > Polyline_t; typedef Polyline_t::const_iterator Polyline_t_cit; double PolylineLength(const Polyline_t& line) { double len = 0.0; Po...
1,382,217
1,382,399
Should I be worried about g++ warnings saying 'inlining failed'?
In a project I'm working on at the office, when we compile a release build (with -Os) we get hundreds of warnings from g++ saying that inlining has failed. Most of these warnings seem to come from boost, however some come from our own library headers (binary .dylibs that we're linking to). Can these warnings generall...
g++ is alerting at what's essentially, strictly a PERFORMANCE problem -- you're requesting inline implementations that just can't be inlined. If your use of inline doesn't really matter, you should remove it (compilers ARE able to inline functions without that hint, you know!-), but in terms of code correctness, you c...
1,382,273
1,382,361
Sorting a Doubly Linked List C++
Trying to do it through a loop that traverses through the list. In the loop I'm feeding the head node into a sorting function that I have defined and then I'm using strcmp to find out if which name in the node should come first. It is not working because writing the names too early. Im comparing them all linearly by ...
From what I understand, you want list::sort to find the least node in the list which is greater than the input. To do this, you need to iterate through all the elements and keep the current least-but-greater node found. Something like this: node * const list::sort( node * given_node ) const { if ( given_node == NUL...
1,382,318
1,382,630
Binding lvalue to a reference
I think I am missing smth back in my theoretical background on this thing. I know there were similar posts but I still do not get it. I have such a code: void somefunc1(Word &Key) { somefunc2(Key); } void somefunc2(char &char1) { return; } compiler generates me an error here: somefunc2(Key); [BCC32 Error] Un...
Temporaries cannot be bound to non-constant references. You should have written this: void somefunc2(const char &char1) { return; }
1,382,459
1,382,479
My 'cout' isn't giving correct value - why?
Simple "sum of digits" code. It compiles but when executed, the last cout gives a "0" for the num int rather than the actual user-input number. Feel free to copy and paste this into your own compiler, if you're so inclined, to see what I mean. How can I get this to output the correct "num" value? ~~~ #include <iostrea...
You've been modifying num all along until it becomes 0 (that's what your while ( num > 0 ) statement ensures!), so OF COURSE it's 0 at the end! If you want to emit what it was before, add e.g. int orig=num; before the loop, and emit orig at the end.
1,382,529
1,383,152
Calling C++ (not C) from Common Lisp?
I am wondering if there is some way to call C++ code from Common Lisp (preferably portably, and if not, preferably in SBCL, and if not, well, then Clozure, CLisp or ECL). The C++ would be called inside loops for numeric computation, so it would be nice if calls were fast. CFFI seems to not support this: "The concept c...
Oh, wait! It seems that there is a trick I can use! I write a wrapper in C++, declaring wrapper functions extern "C": #include "lib.h" extern "C" int lib_operate (int i, double *x) { ... } The header file lib.h, which can be called from both C and C++, is: #if __cplusplus extern "C" { #endif int lib_operate (int i, ...
1,382,537
1,383,581
Setting QMainWindow at the center of screen
My QMainWindow contains a QGraphicsView, which should've minimum width and height. So, I've used the following code in the QMainWindow constructor: ui.graphicsView->setMinimumHeight(VIEWWIDTH); ui.graphicsView->setMinimumWidth(VIEWWIDTH); Then I used following code to set QMainWindow at the center of the screen: QRect...
The problem you are encountering is that Qt will delay many calculations as long as it can. When you set the minimum width and height of your graphics view, it sets a flag somewhere that the window the graphics view is in needs re-layed out. However, it won't do that until it has to... a few milliseconds before it is...
1,382,540
1,382,566
Static cast vs. dymamic cast for traversing inheritance hierarchies
I saw one book on C++ mentioning that navigating inheritance hierarchies using static cast is more efficient than using dynamic cast. Example: #include <iostream> #include <typeinfo> using namespace std; class Shape { public: virtual ~Shape() {}; }; class Circle : public Shape {}; class Square : public Shape {}; clas...
static_cast per se DOESN'T need RTTI -- typeid does (as does dynamic_cast), but that's a completely different issue. Most casts are just telling the compiler "trust me, I know what I'm doing" -- dynamic_cast is the exception, it asks the compiler to check at runtime and possibly fail. That's the big performance differe...
1,382,586
1,382,743
Architecture for Qt application with Lua scripting - pause execution
My embedded project contains a Qt application for the PC which is mainly a simulator for debugging and testing. In the application I can create several widgets which represent either my embedded software or simulate the hardware controlled by the application or can generate external inputs for testing. I plan to improv...
Coroutines are one approach to implementing this. Your pauseSimulation() can internally call coroutine.yield(), and be restarted later by a call to coroutine.resume() from the button's action. The problem is that your UI is at the mercy of your script fragments, since the only way to halt a running coroutine is for it ...
1,382,628
1,382,645
STL: Stores references or values?
I've always been a bit confused about how STL containers (vector, list, map...) store values. Do they store references to the values I pass in, or do they copy/copy construct +store the values themselves? For example, int i; vector<int> vec; vec.push_back(i); // does &(vec[0]) == &i; and class abc; abc inst; vector<ab...
STL Containers copy-construct and store values that you pass in. If you want to store objects in a container without copying them, I would suggest storing a pointer to the object in the container: class abc; abc inst; vector<abc *> vec; vec.push_back(&inst); This is the most logical way to implement the container clas...
1,383,038
1,383,124
3d Realtime Software Renderer Open Source
Is there a good 3d realtime software renderer with features similar to OpenGL/DirectX? Something similar of what cairo or anti-grain do for 2d, but in 3d. I actually just know Mesa witch has a software OpenGL implementation , and Coco3d. It should be open source :)
For a pixel rendering engine why not have look at the DOOM rendering engine sources. Another smaller and more standard API/OpenGL implementation called TinyGL could be something to look at too.
1,383,465
1,400,047
How can I append images to a multi-page image?
I need to programatically append to a multi-page TIFF or PDF a new image. The problem is that the individual images (that compose the multi-page one) have large resolutions and ImageMagick first loads the entire multi-page image into memory, which consumes all the system's memory. I need to be able to append to a multi...
I'm not sure it's possible in ImageMagick. For TIFF, what you need to do is read TIFF Directories out of one TIFF and create new ones in the one you are appending to, and then copy the encoded image via a buffer. There is no need to decode the image to do this, but you have to be careful to do it correctly and bring...
1,383,485
1,383,522
Call a function lower in the script from a function higher in the script
I'm trying to come up with a way to make the computer do some work for me. I'm using SIMD (SSE2 & SSE3) to calculate the cross product, and I was wondering if it could go any faster. Currently I have the following: const int maskShuffleCross1 = _MM_SHUFFLE(3,0,2,1); // y z x const int maskShuffleCross2 = _MM_SHUFFLE(3,...
Just to confirm, your problem is that functions arranged like this don't work, because doStuff isn't declared by the time you call it from getFoo: int getFoo(int bar) { doStuff(bar + 1); } int doStuff(bar) { if (bar == 2) { return getFoo(bar); } return bar * 8; } To fix this, you need to make...
1,383,617
1,383,638
How to check if a file exists and is readable in C++?
I've got a fstream my_file("test.txt"), but I don't know if test.txt exists. In case it exists, I would like to know if I can read it, too. How to do that? I use Linux.
I would probably go with: ifstream my_file("test.txt"); if (my_file.good()) { // read away } The good method checks if the stream is ready to be read from.
1,383,650
1,383,672
C++ Inheritance/VTable questions
Update: Replaced the destructor example with a straight up method call example. Hi, If I have the following code: class a { public: virtual void func0(); // a has a VTable now void func1(); }; class b : public a { public: void func0() { a::func0(); } void func2(); }; Is there a VTable in B? B has no ...
If you declare virtual functions you should also declare your destructor virtual ;-). B has a virtual table, because it has a virtual function, namely func0(). If you declare a function (including a destructor) virtual in a base class, all its derived classes will have the function with same signature virtual as well...
1,384,007
1,384,044
Conversion constructor vs. conversion operator: precedence
Reading some questions here on SO about conversion operators and constructors got me thinking about the interaction between them, namely when there is an 'ambiguous' call. Consider the following code: class A; class B { public: B(){} B(const A&) //conversion constructor { ...
You do copy initialization, and the candidate functions that are considered to do the conversions in the conversion sequence are conversion functions and converting constructors. These are in your case B(const A&) operator B() Now, that are the way you declare them. Overload resolution abstracts away from that, and t...
1,384,119
1,388,020
Help with translating this assembly into c
My compiler won't work with an assembly file I have and my other compiler that will won't work with the c files I have. I don't understand assembly. I need to move this over but I'm not getting anywhere fast. Is there someone out there that can help? I can't believe there isn't a translator available. Here is the b...
STATUS is a built-in register in the PIC architecture, that implements the same functionality as the "status" or "condition" flags register in most larger CPU:s. It contains bitflags that are set and cleared by the microcontroller as it executes code, telling you the result of operations. The Z flag, for instance, is s...
1,384,125
20,020,321
(C++) MessageBox for Linux like in MS Windows
I need to implement a simple graphical message box for a Linux (SDL) application similar to the Windows MessageBox in C++ (gcc/g++ 4.4.0). All it needs to do is to display a caption, a message and an ok or close button and to return to the calling function when that button is clicked. SDL just uses X(11) to open a wind...
In SDL2, you can now show message boxes: http://wiki.libsdl.org/SDL_ShowSimpleMessageBox int SDL_ShowSimpleMessageBox(Uint32 flags, const char* title, const char* message, SDL_Window* window) http://wiki.libsdl.org/SDL_ShowMess...
1,384,326
1,385,031
C++: Optimize using templates variables
Currently, I have some code as follows template<typename Type> Type* getValue(std::string name, bool tryUseGetter = true) { if(tryUseGetter) { if(_properties[name]->hasGetter) { return (Type*)_properties[name]->getter(); } return (Type*)_properties[name]->data; } ...
You could use type cast operator and structure getValue as follows (usage syntax will be the same as with function) : template<typename Type, bool tryUseGetter = true> struct getValue {}; template<typename Type> struct getValue<Type, true> { getValue(const std::string& name) : name(name) {}; operator Type*() ...
1,384,348
1,384,352
"rounding" with integers
I'm trying to get rid of floats in my functions. I have one function that operates on a 16 bit integer value which is an upscaled 8 bit value. Then a downscaled 8 bit is sent to the output. I'm sure I'm not explaining it well. Something like this: int8 spot_value = 21; //arbitrary. just need a starting point int16 r...
You could add 1/2 to the value. In your scaled system that's 128. int8 spot_value = 21; //arbitrary. just need a starting point int16 running_value; running_value = spot_value << 8; //multiply by 256 which is 5376 running_value += 154; //my upscaled value is now 5530 spot_value = running_value + 128; //add an addi...
1,384,409
1,384,420
Visual Studio 2008 C++ language support?
I've been developing a couple of C# tools recently, but primarily working with a lot of legacy Visual Basic 6.0 code (I know, I know...). For the C# development, I've been using Visual Studio 2008 Professional edition that I downloaded using our MSDN subscription here at work. But, as a change of pace over the week...
It sounds like you haven't got it installed. Go to Add/Remove Programs (or Programs and Features, or whatever Windows 7 calls it) and modify your installation. You'll get a list of checkboxes so you can install C#, VB.NET, Crystal Reports etc... and Visual C++. Check that checkbox and wait the hour or so for the insta...
1,384,458
1,559,385
Developing custom list control in 5th edition
If a custom list control is to be developed for S60 5th edition phones, what is the best approach to do that? The control should enable rich presentation of data in custom layouts. It should be possible to include images, texts, buttons in every item. Each list item should be able to expand/collapse to provide more det...
Subclassing listboxes in S60 (Avkon) is a major pain. I've done this a few times, more or less successfully, ususally less. It is telling that Jan-Ole wrote his custom list box for Gravity, it probably spared him a lot of effort and made the UI experience better. So either write something from scratch that just draws o...
1,384,946
1,384,951
Force Preprocessor to use a previous definition in a redefinition
Update 3: Never mind. I kinda got what I was looking for. The following gives unique identifiers inside a class. static const int _counter_start = __COUNTER__; static const int val1 = __COUNTER__ - _counter_start; static const int val2 = __COUNTER__ - _counter_start; Update 2: Boost Preprocessor I will be implementin...
Succinctly, you can't. At the time when CUR is expanded (after the second #define), the preprocessor will replace an instance of CUR with CUR + 2, and 'blue paint' the name CUR (not expanding it any further). Thereafter, the C compiler sees CUR + 2, which most likely yields a compilation error.
1,385,709
1,385,777
Cross-platform primitive data types in C++
Unlike Java or C#, primitive data types in C++ can vary in size depending on the platform. For example, int is not guaranteed to be a 32-bit integer. Various compiler environments define data types such as uint32 or dword for this purpose, but there seems to be no standard include file for fixed-size data types. What ...
I found this header particularly useful: BOOST cstdint Usually better than inventing own wheel (which incurs the maintenance and testing).
1,385,819
1,385,834
Fill an ellipse in C++
I'm trying to make a simple drawing app in c++, but i'm having trouble finding a function that fills an ellipse, all i have found is FillRect, could someone lead me in the right direction? Thanks
See Ellipse: The Ellipse function draws an ellipse. The center of the ellipse is the center of the specified bounding rectangle. The ellipse is outlined by using the current pen and is filled by using the current brush.
1,385,890
1,385,991
Reducing installation of libraries
I have a C++ project that have like 15+ external libraries installed with a package mananger. The problem is with the package change, the newest versions of some library break things (like libblob). I wanted to know if it exists a way to not relaying on some package manager for installing our library and to make sure w...
If you don't want to use a package manager, then don't use a package manager. apt is a great tool and is there to help, but you aren't required to use it. On Ubuntu, you might want to just use dpkg instead of apt and so that none of the dependencies will be automatically updated and avoid upgrading the libraries that a...
1,386,075
1,386,086
Overloading operator [] for a sparse vector
I'm trying to create a "sparse" vector class in C++, like so: template<typename V, V Default> class SparseVector { ... } Internally, it will be represented by an std::map<int, V> (where V is the type of value stored). If an element is not present in the map, we will pretend that it is equal to the value Default fr...
There may be some very simple trick, but otherwise I think operator[] only has to return something which can be assigned from V (and converted to V), not necessarily a V&. So I think you need to return some object with an overloaded operator=(const V&), which creates the entry in your sparse container. You will have to...
1,386,142
1,386,157
Handling partial return from recv() TCP in C
I've been reading through Beej's Guide to Network Programming to get a handle on TCP connections. In one of the samples the client code for a simple TCP stream client looks like: if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); exit(1); } buf[numbytes] = '\0'; printf("Client: rece...
Yes, you will need multiple recv() calls, until you have all data. To know when that is, using the return status from recv() is no good - it only tells you how many bytes you have received, not how many bytes are available, as some may still be in transit. It is better if the data you receive somehow encodes the length...
1,386,183
1,386,390
How to call a templated function if it exists, and something else otherwise?
I want to do something like template <typename T> void foo(const T& t) { IF bar(t) would compile bar(t); ELSE baz(t); } I thought that something using enable_if would do the job here, splitting up foo into two pieces, but I can't seem to work out the details. What's the simplest way of achieving this...
There are two lookups that are done for the name bar. One is the unqualified lookup at the definition context of foo. The other is argument dependent lookup at each instantiation context (but the result of the lookup at each instantiation context is not allowed to change behavior between two different instantiation con...
1,386,319
1,389,157
How to kill XtAppMainLoop (Motif)?
I want to use XmCreate{Error|Warning|Info}Dialog to display some message in screen in my SDL based application before its main window is open and any program data is available. I want the dialog to open, print the intended message, and when the user clicks on the OK button, the dialog plus the top widget I had to creat...
After hours and hours of googling and reading I have found out that you can use XtAppSetExitFlag (XtAppContext).
1,386,674
3,027,284
Syntax coloring of own types in Visual Studio (C++)
How can I get Visual Studio to highlight my own class types? This works fine for C# but not for C++...
For those running Visual Studio 2010 Highlighterr may fit your needs. It's also in the MSDN Visual Studio Gallery. It leverages the improved C++ IntelliSense in 2010. It makes you set special highlighters in Environment -> Fonts and Colors for the types it detects, but overall it works quite well from what I've seen.
1,386,780
1,386,786
What is the cleanest way to include and access binary data in VC++ Express?
I have some binary files that I'd like to embed in a dll I'm compiling with VC++ Express Edition. I have a couple ways to do it (like converting the data to arrays that I compile along with the code), but I'm not satisfied and I feel like I'm probably missing an easy, straightforward solution. What's the cleanest, easi...
I don't know if this is an option, but the Unix (and probably easily avaliable on Windows) program xxd has an option to output a C header: xxd -i file.bin > file.h file.h will contain the definition of an array of unsigned char containing the data and an unsigned int that tells you the length of the array. Of course, ...
1,387,095
1,388,073
Learn C++ to understand examples in book fast, know C and Java already
I need to read "A Practical Introduction to Data Structures and Algorithm Analysis" by Shaffer for class but the code examples in the book are all in C++ which I do not know. I know C and Java already and was wondering if you knew any resources that helped learn enough C++ to understand these examples fast if you alrea...
Another free textbook is The C++ Annotations by Frank B. Brokken. You can browse it online, or you can download the pdf version. A quote from the first page: This document is intended for knowledgeable users of C (or any other language using a C-like grammar, like Perl or Java) who would like to know more abou...
1,387,101
1,387,140
C++ Class instance array initialization
I have a class A as follows: class A { public: A() { printf("A constructed\n"); } ~A(); //no other constructors/assignment operators } I have the following elsewhere A * _a; I initalize it with: int count = ... ... _a = new A[count]; and I access it with int key =...
This can mean that key or count contains an uninitialized value. Even if you do initialize it in the declaration, e.g. int key = foo + bar;, it could be that either foo or bar is uninitialized, and valgrind carries this over to key.
1,387,206
1,487,332
Using friends with base classes for Boost Parameter
I'm using the Boost Parameter tutorial to create a named-parameter constructor for a playing card generator. The tutorial says to put the ArgumentPack into a base class, but I want to modify variables in the card generator class. I've thought about doing this: class CGconstructor_base { public: template<class Arg...
I think we need some cleanup. the friend declaration seems ill-placed, from the comment you want CGconstructor_base to be able to access CardGenerator attributes: if this is so, then the friend declaration goes into CardGenerator (I say who I consider as my friends, you do not declare yourself as being someone I consi...
1,387,263
1,387,278
C++: Hide base static member
In C++, is it possible to have a child class "hide" a base class' static fields and methods? (i.e. A has a field named ABC of type int, B:A and B has a field named ABC of type int)
#include <iostream> using namespace std; class A{ public: static int a; }; class B: public A{ public: static int a; // hide base member }; int A::a; int B::a; int main(){ A::a=10; B::a=20; B k; cout << "\n" << B::a << k.a; return 0; }
1,387,348
1,387,368
What are efficient ways to debug an optimized C/C++ program?
Many times I work with optimized code (sometimes even involving vectorized loops), which contain bugs and such. How would one debug such code? I'm looking for any kind of tools or techniques. I use the following (possibly outdated) tools, so I'm looking to upgrade. I use the following: Since with ddd, you cannot see t...
It is always harder to debug optimised programs, but there are always ways. Some additional tips: Make a debug build, and see if you get the same bug in a debug build. No point debugging an optimised version if you don't have to. Use valgrind if on a platform that supports it. The errors you see may be harder to under...
1,387,460
1,399,123
C++ Stack by Array Implementation
What I want to happen is for the pushFront(int) function to do this: bool stack::pushFront( const int n ) { items[++top] = n; // where top is the top of the stack return true; // only return true when the push is successful } items is a struct type of the object "item". Have a look: class stack { stack(int ca...
bool stack::pushFront( const int n ) { if(top == maxSize-1) return false; items[++top].n = n; // where top is the top of the stack return true; // only return true when the push is successful }
1,387,535
1,387,666
C++: Convert Macro based Property System to use templates
I've already implemented, using macros, a C++ property system that satisfied the following requirements: Property can be referenced using a integeral key Property can be accessed via a generic Set/Get Properties (and property keys) must be inheritable Properties can be registered with getters/setters and is implement...
This looks like a classic game property system so I'm going to recommend you read this Gamasutra article about a good system that doesn't require too much gunk around your code. Also have a look at boost.fusion and see if it can't help you. What follows is my opinion and can be ignored for the sake of the question: Tha...
1,387,609
1,388,015
How do I use a pointer to char from SWIG, in Perl?
I used SWIG to generate a Perl module for a C++ program. I have one function in the C++ code which returns a "char pointer". Now I dont know how to print or get the returned char pointer in Perl. Sample C code: char* result() { return "i want to get this in perl"; } I want to invoke this function "result" in...
Depending on the complexity of the C++ interface, it may be easier, faster, and more maintainable to skip SWIG and write the XS code yourself. XS&C++ is a bit of an arcane art. That's why there is Mattia Barbon's excellent ExtUtils::XSpp module on CPAN. It make wrapping C++ easy (and almost fun). The ExtUtils::XSpp dis...
1,387,647
1,387,747
Persistant references in STL Containers
When using C++ STL containers, under what conditions must reference values be accessed? For example are any references invalidated after the next function call to the container? { std::vector<int> vector; vector.push_back (1); vector.push_back (2); vector.push_back (3); vector[0] = 10; //modifies 0'th element i...
About inserting into vectors, the standard says in 23.2.4.3/1: [insert()] causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid. (Although this in fact this talks about insert(), Table 68 ind...
1,387,769
2,069,565
Create registry entry to associate file extension with application in C++
I would like to know the cleanest way of registering a file extension with my C++ application so that when a data file associated with my program is double clicked, the application is opened and the filename is passed as a parameter to the application. Currently, I do this through my wix installer, but there are some ...
Your basic overview of the process is found in this MSDN article. The key parts are at the bottom of the list: Register the ProgID A ProgID (essentially, the file type registry key) is what contains your important file type properties, such as icon, description, and context menu items including applications used when...
1,387,906
1,387,977
C++ with Python embedding: crash if Python not installed
I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing. I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embeddin...
In addition to pythonxy.dll, you also need the entire Python library, i.e. the contents of the lib folder, plus the extension modules, i.e. the contents of the DLLs folder. Without the standard library, Python won't even start, since it tries to find os.py (in 3.x; string.py in 2.x). On startup, it imports a number of ...
1,388,065
1,388,085
How to effectively delete C++ objects stored in multiple containers? auto_ptr?
I have an application which creates objects of a certain kind (let's say, of "Foo" class) during execution, to track some statistics, and insert them into one or both of two STL maps, say: map<Foo*, int> map1; map<Foo*, int> map2; I was wondering what is the best way to delete the Foo objects. At the moment my solutio...
auto_ptr objects cannot, as you say, be stored in STL containers. I like to use the shared_ptr object (from boost) for this purpose. It is a referenced counted pointer, so the object will be deleted once only, when it goes out of scope. typedef<shared_ptr<Foo>, int> Map; Map map1; Map map2; Now, you just add and remov...
1,388,136
1,388,158
Generating HTML (i.e. br and p tags) from plaintext in C++
I've got a bunch of text like this: foo bar baz What's likely to be the most efficient way in C++ of transforming that to this: <p>foo<br />bar</p> <p>baz</p> for large(ish) quantities of text (up to 8000 characters). I'm happy to use boost's regex_replace, but I was wondering if string searching for \n\n might be m...
I would use a simple state-machine. It does require comparison of the state for each time through the loop, but it should not matter (it could be optimised by having a sub loop in the third state - see below). The start state would be the same as when two newlines have be encountered. There would be a variable for...
1,388,230
1,391,665
VC6 and template error
I am overloading operator << to implement a stream like interface for a class: template<typename T> CAudit& operator << ( const T& data ) { audittext << data; return *this; } CAudit& operator << ( LPCSTR data ) { audittext << data; return *this; } The template version fails to compile with "fatal err...
That overload of the template for function pointers surely is too much for good old Visual Studio 6. As a workaround you could define a type for your manipulator and overload operator<< for that type. Here's some code: #include "stdafx.h" #include <string> #include <iostream> #include <sstream> #include <windows.h> cl...
1,388,469
1,388,493
Is there a working C++ refactoring tool?
Does anybody know a fully featured refactoring tool for C++ that works reliably with large code bases (some 100.000 lines)? I tried whatever i can find again and again over the last years: SlickEdit, Eclipse CDT. They all were not at all usable. SUMMARY: I took time and evaluated "Visual Assist X" as well as "Refactor...
I find Visual Assist X with Visual Studio very useful. Another choice is Refactor for C++.
1,388,597
1,388,642
std::vector and c-style arrays
I am experimenting with OpenCL to increase the speed of our software. We work with maps a lot and, to simplify, represent a map as a std::vector< std::vector >. The OpenCL API takes raw c-style pointers as arguments, for example int* in the case above. My questions: Are there implementation guarantees in the stl that ...
Are there implementation guarantees in the stl that vector is, internally, consecutive in memory? As of C++03, yes, a vector is guaranteed to use contiguous storage. (In C++98, there was an accidental loophole so an implementation could hypothetically use non-contiguous storage, but it was fixed in the 2003 revision ...
1,388,608
1,388,670
How to work around Visual Studio Compiler crashes
We have a large Visual Studio 2005 C++/Mfc solution, 1 project with around 1300 source files (so about 650 .h and 650 .cpp files). We also use Boost and a few other libraries (COM: MSXML, Office). Recently, I've added a few instances of boost::multi_index to speed up things a bit. This all compiles most of the time. B...
If 1300 files are taking THAT long to compile then you are including waaaay too many header files that are unncecessary. I'd guess people have cut and pasted a bunch of headre files into a CPP file without thinking which headers they actually need so that loads of them are getting included when they ought not to be. ...
1,388,685
1,388,752
Local variable scope question
Why is the following code prints "xxY"? Shouldn't local variables live in the scope of whole function? Can I use such behavior or this will be changed in future C++ standard? I thought that according to C++ Standard 3.3.2 "A name declared in a block is local to that block. Its potential scope begins at its point of dec...
You quoted standard correctly. Let me emphasize: A name declared in a block is local to that block. Its potential scope begins at its point of declaration and ends at the end of its declarative region. You didn't declare any name, actually. Your line MyClass (12345); does not even contain a declaration! What it ...
1,389,082
1,390,016
IPv6 address validation and canonicalization
What libs have you used for that? How compatible are they with one another? Or did you write your own parsing routine? I'm particularly interested in mutually-compatible implementations for Java, C++, Python, and JavaScript, which support: zero compression ("::") IPv4-mapped addresses ("::ffff:123.45.67.89") canonic...
On POSIX systems you can use inet_pton and inet_ntop in combination to do canonicalization. You will still have to do your own CIDR parsing. Fortunately, I believe the only valid CIDR syntax for IPv6 is the /number_of_bits notation, so that's fairly easy. The other issue you will run into is the lack of support for i...
1,389,167
1,393,776
Motif main window w/o system menu, minimize and maximize boxes how? (C++)
How do I create a Motif main window that doesn't have a system menu, minimize and maximize boxes? I just cannot find out how by googling and reading docs and tutorials. I believe that it should be possible with some additional parameters for XtVaCreateManagedWindow, but which? I have tried several variants of XtVaSetVa...
Apparently it's not (easily) possible to get rid of the window (system) menu, but it seems to be possible to disable window menu items with some code like this: int i; XtVaGetValues (widget, XmNmwmFunctions, &i); i &= ~(MWM_FUNC_ALL | MWM_FUNC_MINIMIZE | MWM_FUNC_MAXIMIZE | MWM_FUNC_CLOSE); XtVaSetValues (widget, XmNmw...
1,389,337
1,389,403
Singletons via static instance in C++ -- into source or into header files?
Cheers, I ran into this chunk of code in "Programming Game AI by Example": /* ------------------ MyClass.h -------------------- */ #ifndef MY_SINGLETON #define MY_SINGLETON class MyClass { private: // member data int m_iNum; //constructor is private MyClass(){} //copy ctor and assignment should be private...
In C++ nothing prevent an inline function to have a static variable and the compiler has to arrange to make that variable common between all translation units (like it has to do it for template instantiation static class members and static function variables). 7.1.2/4 A static variable in an extern inline function al...
1,389,402
1,389,492
std c++ container element destruction and insertion behaviour
I have made the following little Program: (basically a class that couts if it gets created, copied or destroyed and a main that does some of that) class Foo { public: Foo(string name): _name(name) { cout << "Instance " << _name << " of Foo created!" << std::endl; }; Foo(const Foo& other): _name(other._name) { ...
Why do I even bother passing something as a reference if it gets copied twice anyway? You should consider STL container types as blackbox that can copy the objects you store as often as they need to. For instance, every time the container is resized, all of the objects will be copied. It is possible that your compile...
1,389,414
1,389,766
Motif: Intercept close box event and prevent application exit? (C++)
How do I intercept when the user clicks on a motif window's (widget's) close box, and how do I prevent the Motif window manager to close the entire calling application on the close box being clicked (so that my app can close the Motif application context and windows and continue to run)? I've tried to find out myself w...
This seems to work (found on the inet): #include <Xm/Protocols.h> Boolean SetCloseCallBack (Widget shell, void (*callback) (Widget, XtPointer, XtPointer)) { extern Atom XmInternAtom (Display *, char *, Boolean); if (!shell) return False; Display* disp = XtDisplay (shell); if (!disp) return False; // Retrieve ...
1,389,538
1,389,813
Cancelling std::cout code lines using preprocessor
One can remove all calls to printf() using #define printf. What if I have a lot of debug prints like std::cout << x << endl; ? How can I quickly switch off cout << statements in a single file using preprocessor?
NullStream can be a good solution if you are looking for something quick that removes debug statements. However I would recommend creating your own class for debugging, that can be expanded as needed when more debug functionality is required: class MyDebug { std::ostream & stream; public: MyDebug(std::ostream...
1,389,680
1,389,689
Why is Qt looking for my slot in the base class instead of derived one?
I have my class X which inherits from Qt's class Base. I declared and defined void mySlot() slot in my class X and I'm connecting some signal to this slot in X's constructor. However, when running my program I get an error message saying there's no such slot as void mySlot() in the class Base. Why is the code generated...
Did you add the Q_OBJECT macro on the derived class?
1,389,838
1,391,012
How to debug macros efficiently in VS?
I've got a pretty complicated macro inside my (unmanaged) C++ code. Is there any way to expand macros in VS debugger? Or maybe there is another way to debug macros there? F.e. I'd like to place a breakpoint inside it. (Yes, I know macros are bad.)
Go to either project or source file properties by right-clicking and going to "Properties". Under Configuration Properties->C/C++->Preprocessor, set "Generate Preprocessed File" to either with or without line numbers, whichever you prefer. This will show what your macro expands to in context. If you need to debug it on...
1,389,899
1,389,906
C++ Copy Constructor Syntax
I apologize in advance, my C++ is rusty... What does : m_nSize(sizeof(t1)) mean in the following section? class CTypeSize { public: template<class T> CTypeSize(const T &t1) : m_nSize(sizeof(t1)) { } ~CTypeSize(void){ }; int getSize(void) const{ return m_nSize; } private:...
It has nothing todo with copy ctor. You are initializing the variable m_nSize using initializer list with the sizeof the template argument t1.