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
2,135,840
2,135,868
What's the best way to force the user of a C++ function to acknowledge the semantic meaning of parameters that are numerical constants?
I'd like to write function interfaces that force the user to acknowledge the semantic meaning of built-in constants. For example, I'd like to take void rotate(float angle); // Rotate the world by an angle in radians. and change it to void rotate(Radians angle); Am I right in believing that the problem with making a R...
No, it is possible to make a Radians class that should be optimized by most decent compilers into something that's no slower than a plain float. You might be interested in boost.units. In fact, with boost.units you can even set it up so that if someone wants to pass in an angle in degrees it will automatically be conv...
2,135,888
2,135,916
How do I add an object to a vector<const Obj&>?
I am not sure why this doesn't compile: std::vector< const Obj& > myVector; void foo(const Obj& obj) { myVector.push_back( obj ); } Sorry, a bit of additional info on what I'm trying to achieve: I can't change the signature of foo without breaking an interface, but I just want to hang onto the Objects that g...
You can't have an vector of references. as the things in a vector must be copyable and assignable, and references are neither of these. You probably want a vector of pointers: std::vector< const Obj * > myVector; void foo( const Obj & obj ) { myVector.push_back( & obj ); }
2,135,981
2,136,013
What is the cleanest way to create a timeout for a while loop?
Windows API/C/C++ 1. .... 2. .... 3. .... 4. while (flag1 != flag2) 5. { 6. SleepEx(100,FALSE); //waiting for flags to be equal (flags are set from another thread). 7. } 8. ..... 9. ..... If the flags don't equal each other after 7 seconds, I would like to continue to line 8. Any help ...
If you are waiting for a particular flag to be set or a time to be reached, a much cleaner solution may be to use an auto / manual reset event. These are designed for signalling conditions between threads and have very rich APIs designed on top of them. For instance you could use the WaitForMultipleObjects API which ...
2,136,053
2,136,150
std::map inizialitazion (only one time)
I have a function that translates data using std::map struct HistoParameter { int nbins; float first; float last; HistoParameter(int _nbins, int _first, int _last) : nbins(_nbins), first(_first), last(_last) {}; }; HistoParameter* variable_to_parameter(char* var_name) { std::map<const std::string, HistoP...
Your second solution should certainly improve efficiency, but isn't (at least IMO) the best implementation possible. First of all, it makes first_time publicly visible, even though only variable_to_parameter actually cares about it. You've already made hp a static variable in the function, and first_time should be as w...
2,136,153
2,136,220
g++ alignment problem
I have the following code: #include <stdio.h> int main(void) { int x __attribute__ ((aligned (16))) = 0; printf("%lX\n", &x); return 0; } Compiling and running this code using mingw32-c++.exe (GCC) 3.4.5 (mingw-vista special r3) prints 0x22FF24 which is 0b1000101111111100100100. Compiling and running thi...
16=24, so I would expect the last 4 bits of the address to be zero if the address was aligned to a 16-byte boundary. The stack is generally not guaranteed to have any sort of alignment on x86, see Bug 16660. Also, GCC is dependent on the linker for alignment of global/common variables, and binutils prior to 2.20 were ...
2,136,165
2,136,377
Is there something like .dll or .so, but cross-platform?
is there something like .dll or .so, but cross-platform?
It's not clear what you are asking, but if you are asking "how can I make dynamically loadable C/C++ libraries in a cross-platform manner," then the answer is GNU Libtool. It has support for building and consuming them, plus runtime support functions
2,136,244
2,136,266
Unknown error in array initialization: invalid in-class initialization of static data member of non- integral type `const unsigned char[256]'
I was trying to make a Intel 8080 CPU emulator (then I'd like to emulate Space Invaders, which use it). I coded nearly complete implementation of this CPU (thanks to MAME and Tickle project (mostly) ;) ) except undocument instructions (0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x0CB, 0x0D9, 0x0DD, 0x0ED, 0x0FD). I've h...
Like it says, you cannot initialize static non-integral types in a class definition. That is, you could do this: static const unsigned value = 123; static const bool value_again = true; But not anything else. What you should do is place this in your class definition: static const unsigned char cycles_table[256]; And ...
2,136,294
2,140,234
Makefile works %.c, does not work %.cpp
I have a set of makefiles I use to build a 'big' C project. I am now trying to reuse some in my C++ project and have run into this headache that I just cannot figure out. The makefile looks like this SOURCES = \ elements/blue.cpp # Dont edit anything below here VPATH = $(addprefix $(SOURCE_DIR)/, $(dir $(SOURCES))) ...
Ok guys I figured it out here and its a big mess of a bug. After some more experimentation I went to post a bug on the make-bugs list and turned on debug output to tell them exactly what was going on. Turns out I should have done this before because it led me right to the solution. I use an automatic dependency genera...
2,136,411
2,136,434
Apache have shared objects for both windows and linux.How do they do it?
Apache have .so modules for both windows and linux.How do they do it?
Good question, I would suspect they remain dynamic link libraries with different file extensions but I could be wrong. File extension, is, after all, no guarantee of file type. If depends.exe in the Windows SDK can parse them, they're dlls. I have never tried and now can't, no Windows on my pc anymore. Edit: looking at...
2,136,998
2,137,013
Using a STL map of function pointers
I developed a scripting engine that has many built-in functions, so to call any function, my code just went into an if .. else if .. else if wall checking the name but I would like to develop a more efficient solution. Should I use a hashmap with strings as keys and pointers as values? How could I do it by using an STL...
Whatever your function signatures are: typedef void (*ScriptFunction)(void); // function pointer type typedef std::unordered_map<std::string, ScriptFunction> script_map; // ... void some_function() { } // ... script_map m; m.emplace("blah", &some_function); // ... void call_script(const std::string& pFunction) { ...
2,137,361
2,137,371
What is the best way to create a sub array from an exisiting array in C++?
OK, I am trying to get a sub array from an existing array and I'm just not sure how to do it. In my example I have a very large array, but I want to create an array from the last 5 elements of the array. An example of what I am talking about would be: int array1 = {1,2,3,...99,100}; int array2[5] = array1+95; I know t...
for this: "such that array1[96] and array2[0] would be pointing to the same location." you can do: int *arr2 = arr1 + 96; assert(arr2[0] == arr1[96] == 97);
2,137,441
2,137,462
c++ template casting with derived classes
#include <vector> struct A {int a;}; struct B : public A {char b;}; int main() { B b; typedef std::pair<A*, A*> MyPair; std::vector<MyPair> v; v.push_back(std::make_pair(&b, &b)); //compiler error should be here(pair<B*,B*>) return 0; } I don't understand why this compiles (maybe somebody can kindly provid...
std::pair has a constructor template: template<class U, class V> pair(const pair<U, V> &p); "Effects: Initializes members from the corresponding members of the argument, performing implicit conversions as needed." (C++03, 20.2.2/4) Conversion from a derived class pointer to a base class pointer is implicit.
2,137,523
2,137,871
Boost Unit testing with Allegro Graphics Library
I'm trying to use boost unit testing alongside the Allegro graphics library, but both require main() alterations / overwrites. Has anyone had any experience using both? Edit 1/29/2010: I've refrained from selecting an answer until I can verify one or another, and due to the... sparse nature of the answers.
boost.test can be used with or without a main(). look into these macros will give you some idea how to use it properly: //#define BOOST_TEST_MODULE my_test //#define BOOST_TEST_MAIN //#define BOOST_TEST_DYN_LINK //#define BOOST_TEST_NO_MAIN
2,138,110
2,138,181
How does a compiler deal with inlined exported functions?
If a header file contains a function definition it can be inlined by the compiler. If the function is exported, the function's name and implementation must also be made available to clients during linkage. How does a compiler achieve this? Does it both inline the function and provide an implementation for external call...
Header files are just copy-pasted into the source file — that's all #include does. A function is only inline if declared using that keyword or if defined inside the class definition, and inline is only a hint; it doesn't force the compiler to produce different code or prohibit you from doing anything you could otherwis...
2,138,437
2,138,452
Abstract class - hiding implementation in C++ practice
Recently I've been writing code similar to this: messagehandler.h: #include "message.h" class MessageHandler { public: virtual ~MessageHandler() {} virtual void HandleMessage(Message *msg) = 0: }; persistmessagehandler.h: MessageHandler *CreatePersistMessageHandler(); persistmessagehandler.cpp: #include "messag...
You always have to hide as much as possible. Your way (putting implementation classes into .cpp) is a common way to do this in c++.
2,138,460
2,138,643
Stopping an implicit cast on operator delete
My String class provides an operator char* overload to allow you to pass the string to C functions. Unfortunately a colleague of mine just inadvertently discovered a bug. He effectively had the following code. StringT str; // Some code. delete str; Is there anyway to prevent delete from casting the string object to ...
Yes. Provide TWO implicit casts, by declaring (but not defining!) operator char const volatile*. When you're passing your StringT to a C string function, overload resolution will still select your original operator char const* (exact match). But delete str; now becomes ambiguous. The declaration can be private, so if ...
2,138,515
2,138,540
Fast and elegant one-way mapping of known integer values
I have to map a set of known integers to another set of known integers, 1-to-1 relationship, all predefined and so on. So, suppose I have something like this (c++, simplified, but you'll get the idea): struct s { int a; int b; }; s theMap[] = { {2, 5}, {79, 12958 } }; Now given an input integer, say 79, I'd need to f...
Use a map #include <map> #include <iostream> int main() { std::map <int, int> m; m[79] = 12958; std::cout << m[79] << std::endl; } Using a map is the most general solution and the most portable (the C++ standard does not yet support hash tables, but they are a very common extension). It isn't necessariil...
2,138,625
2,138,641
How can I link (C++) with renamed Python .lib and .dll?
When I include "Python.h" from Python 2.5 in a C++ project, it knows through some magical process that it has to link with "python25.lib" and load "python25.dll" at runtime, though I didn't specified anything neither in "Linker -> Additional Dependencies" nor in "Linker -> Additional Library Directories". Now I would l...
MSVC supports this feature through pragmas: #pragma comment(lib, "python25.lib"); More info in MSDN. Look into Python.h file and modify the name of the linkage, if that what you want.
2,138,719
2,138,720
What's the reasoning behind putting constants in 'if' statements first?
I was looking at some example C++ code for a hardware interface I'm working with and noticed a lot of statements along the following lines: if ( NULL == pMsg ) return rv; I'm sure I've heard people say that putting the constant first is a good idea, but why is that? Is it just so that if you have a large statement you...
So that you don't mix comparison (==) with assignment (=). As you know, you can't assign to a constant. If you try, the compiler will give you an error. Basically, it's one of defensive programming techniques. To protect yourself from yourself.
2,139,105
2,139,123
Adding item to list in C++
I am using two classes in my C++ application. The code is as follows: class MyMessageBox { public: void sendMessage(Message *msg, User *recvr); Message receiveMessage(); list<Message> dataMessageList; }; class User { public: MyMessageBox *dataMsgBox; }; The msg is a pointer to a derived class object o...
I don't know what you're trying to do with that msgRef, but it's wrong. Are you an ex-Java programmer, by any chance? If Message is a base class for derivatives of Message, you need to store pointers in the list. Change list<Message> to list<Message*>; and push_back(msgRef) should become push_back(msg), removing the ms...
2,139,124
2,139,136
How to make a Debian package depend on multiple versions of libboost
I have a debian/control file which includes: Build-Depends: ... libboost1.35-dev, libboost-date-time1.35-dev, ... This stops the package from building on modern Ubuntu systems. I could just change all the 1.35s for 1.38s and then it would work on modern Ubuntu, but not older versions. I would like to do something like...
You should "Depends: libboost-dev" unless there is a special reason to target for specific versions of Boost. This libboost-dev package is a pseudo-package that pulls in the suitable version of libboost. If you really want to target them specifically, use the "or" operator: Depends: A | B | C See: http://www.debian.o...
2,139,224
2,139,254
How to pass objects to functions in C++?
I am new to C++ programming, but I have experience in Java. I need guidance on how to pass objects to functions in C++. Do I need to pass pointers, references, or non-pointer and non-reference values? I remember in Java there are no such issues since we pass just the variable that holds reference to the objects. It wou...
Rules of thumb for C++11: Pass by value, except when you do not need ownership of the object and a simple alias will do, in which case you pass by const reference, you must mutate the object, in which case, use pass by a non-const lvalue reference, you pass objects of derived classes as base classes, in which case you...
2,139,335
2,139,376
Which C++ library for ESRI shapefiles to choose?
Does anyone have an experience in processing (reading) ESRI shapefiles from C++? I have found at least 2 open source libraries: ShapeLib C library and OGR. Which one is better? Does anybody used one of them? How about the experience?
I've found them both to be ok, but I'd choose the ShapeLib library as ogr is a bit heavy/weird for its purpose. The shapefile format is very simple; if you only have to access a specific/simple set of shapefiles you could consider reinventing the wheel and write the code to access them yourself. I've done this in an e...
2,139,724
2,141,470
Design options for a C++ thread-safe object cache
I'm in the process of writing a template library for data-caching in C++ where concurrent read can be done and concurrent write too, but not for the same key. The pattern can be explained with the following environment: A mutex for the cache write. A mutex for each key in the cache. This way if a thread requests a ke...
You want to lock and you want to wait. Thus there shall be "conditions" somewhere (as pthread_cond_t on Unix-like systems). I suggest the following: There is a global mutex which is used only to add or remove keys in the map. The map maps keys to values, where values are wrappers. Each wrapper contains a condition and...
2,139,752
2,139,791
Protocol buffers and UTF-8
The history of Encoding Schemes / multiple Operating Systems and Endian-nes have led to a mess in terms of encoding all forms of string data (--i.e., all alphabets); for this reason protocol buffers only deals with ASCII or UTF-8 in its string types, and I can't see any polymorphic overloads that accept the C++ wstring...
It may be overkill, but the ICU libraries will do everything you need and you can use them on both Windows and Linux. However, if you are only wanting conversion, then under Windows, a simple call to MultiByteToWideChar and WideCharToMultiByte can do the conversion between UTF-8 and UTF-16. For example: // utf-8 to u...
2,139,948
2,140,903
Seeking advice on using QGLWidget in Qt4
I'm new here, and have a question about opengl in Qt4, which I've been learning over the last few months. Particularly, I'm seeking advice on the best way to compose a scene in a good object-oriented fashion using the QGLWidget. I'd ideally like every item in my scene to be sub-classes of a super 'Entity' class. Then i...
I agree with Vime: You're building a scene graph, and there are a number of classical approaches for designing its object hierarchy. Check out "3D Game Engine Design," by Dave Eberly, for details on one such engine, and look at OGRE for another example. Since only one GL context can be active at a time on a particular ...
2,140,025
2,140,182
C++ templated constructor won't compile
How come I can't instantiate an object of type Foo with above constructor? I have a class Bar that uses an internal typedef (as a workaround for "template typedefs") and intend to use it in a constructor as below (CASE 1). However, I don't seem to get it to compile. Is this legal C++? CASE 2 seems to suggest the proble...
According to paragraph 14.8.2.1 of the C++ standard, when a template parameter is used only in a non-deduced context, the corresponding template argument cannot be deduced: If a template-parameter is not used in any of the function parameters of a function template, or is used only in a non-deduced context, its corres...
2,140,319
2,140,413
Can I new[], then cast the pointer, then delete[] safely with built-in types in C++?
In my code I have effectively the following: wchar_t* buffer = new wchar_t[size]; // bonus irrelevant code here delete[] reinterpret_cast<char*>( buffer ); Types in question are all built-in and so they have trivial destructors. In VC++ the code above works allright - new[] just allocates memory, then delete[] just fr...
My initial thought was that it is undefined behavior. 5.3.5/3: "In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.73). Footnote 73 reads, "This implies that an object cannot be deleted using a pointer of type void* be...
2,140,536
2,140,791
G++ CAS (__sync_val_compare_and_swap) problem needs explaining
This is doing my head in. I'm trying to implement some "lock-free" code and am using CAS (gcc __sync_val_compare_and_swap) to do he heavy lifting. My problem can be shown with the following code. volatile bool lock; void *locktest( void *arg ) { for ( int i = 0 ; i < 100000 ; ++i ) { // acquire a lock ...
It looks to me like __sync_val_compare_and_swap will always return the old value of the variable, even if no swap took place. In this case, suppose another thread holds the lock just before you try to acquire it - then lock is true, and you're calling __sync_val_compare_and_swap(&lock, true, true);. Just before the a...
2,140,619
2,140,781
Correct way to check if Windows is 64 bit or not, on runtime? (C++)
bool Win64bit = (sizeof(int*) == 8) ? 1 : 0; I need this so my app can use Windows registry functions properly (or do i need?). So am i doing it right ?
Here's what Raymond Chen suggests in his blog at https://devblogs.microsoft.com/oldnewthing/20050201-00/?p=36553: BOOL Is64BitWindows() { #if defined(_WIN64) return TRUE; // 64-bit programs run only on Win64 #elif defined(_WIN32) // 32-bit programs run on both 32-bit and 64-bit Windows ...
2,140,629
2,140,658
What's the real utility of make and ant?
While i'm developing in C/C++ and Java, i simply make a compile.bat script that does everything, that's fine for me. Why should i use make and why should i use ant?
Suppose you have 1000 source files and change just one of them. With your .bat script you will have to recompile the lot, with make you recompile just the one that changed. This can save quite a bit (read hours on a big project) of time. Even better, if you change one of your header files, make will re-compile only the...
2,140,796
2,141,680
Draw a multiple lines set with VTK
Can somebody point me in the right direction of how to draw a multiple lines that seem connected? I found vtkLine and its SetPoint1 and SetPoint2 functions. Then I found vtkPolyLine, but there doesn't seem to be any add, insert or set function for this. Same for vtkPolyVertex. Is there a basic function that allows me t...
For drawing multiple lines, you should first create a vtkPoints class that contains all the points, and then add in connectivity info for the points you would like connected into lines through either vtkPolyData or vtkUnstructuredGrid (which is your vtkDataSet class; a vtkDataSet class contains vtkPoints as well as the...
2,140,841
2,140,866
How to avoid out parameters?
I've seen numerous arguments that using a return value is preferable to out parameters. I am convinced of the reasons why to avoid them, but I find myself unsure if I'm running into cases where it is unavoidable. Part One of my question is: What are some of your favorite/common ways of getting around using an out para...
I'm not sure why you're trying to avoid passing references here. It's pretty much these situations that pass-by-reference semantics exist. The code static void doWork(ExpensiveCopy& ec_out, int someParam); looks perfectly fine to me. If you really want to modify it then you've got a couple of options Move doWork so...
2,140,984
3,348,738
WebKit CSS 3d transforms not working in Snow Leopard
I've compiled an application that uses WebKit on Leopard (10.5). The application is 32 bit. I've bundled 32 bit versions of WebKit/WebCore etc with the app. If I run it on Snow Leopard (10.6) none of the CSS 3d transforms work. 3D transforms work in SL's Safari. I have a feeling that my app isn't able to link with some...
I ran into a similar problem. My goal was saving an image of a WebKit/WebView, but anything with -webkit-transform rendered blank. This is the code I was using that did not work correctly: -(NSBitmapImageRep *)getBitmap { return [[NSBitmapImageRep alloc] initWithFocusedViewRect: [[[[webView mainFrame] frameView] do...
2,141,023
2,141,035
Do the class specific new delete operators have to be declared static
Is it required in standard for class specific new, new[], delete, and delete[] to be static. Can i make them non-static member operators. And why is it required for them to be static
Yes it's required for them to be static. They are used to allocate memory for an object that does not yet exist hence there is no instance to refer to.
2,141,105
2,141,182
problem with different linux distribution with c++ executable
I have a c++ code that runs perfect on my linux machine (Ubuntu Karmic). When I try to run it on another version, I have all sort of shared libraries missing. Is there any way to merge all shared libraries into single executable? Edit: I think I've asked the wrong question. I should have ask for a way to static-link my...
There are 3 possible reasons you have shared libraries missing: you are using shared libraries which do not exist by default on the other distribution, or you have installed them on your host, but not the other one, e.g. libDBI.so you have over-specified the version at link time, e.g. libz.so.1.2.3 and the other machi...
2,141,188
2,141,338
Changing Function Access Mode in Derived Class
Consider the following snippet: struct Base { virtual ~Base() {} virtual void Foo() const = 0; // Public }; class Child : public Base { virtual void Foo() const {} // Private }; int main() { Child child; child.Foo(); // Won't work. Foo is private in this context. static_cast<Base&> (child).Foo(); // Ok...
Yes, changing the access mode in derived classes is legal. This is similar in form but different in intent to the Non-Virtual Interface idiom. Some rationale is given here: The point is that virtual functions exist to allow customization; unless they also need to be invoked directly from within derived classes' code, ...
2,141,346
2,141,561
Opinions on not using prototypes for static functions
Does anyone have any opinions on not using prototypes unless necessary for functions declared "static". Do you always put them at the top of your translation unit? I tend to but recently I've been thinking about why not rely on the ordering of the functions and in way you can limit some scope of where the function can ...
I follow the "define before use" rule myself wherever possible (thus my files always read from the bottom up). That way I don't have to worry about keeping declarations and definitions in sync, at least within the same file. To be pedantic, you're talking about declarations, not prototypes; prototype refers to the s...
2,141,608
2,141,715
STL priority_queue copies comparator class
I'm trying to create a priority queue with a custom comparator: std::priority_queue<int, std::vector<int>, MyComparator> pq; My problem is that MyComparator has a method that stores additional state. Because MyComparator is copied to the priority queue (as far as I can tell), there's no way for me to call this method ...
Comparison objects used in STL containers as well as predicates used in STL algorithms must be copyable objects and methods and algorthims are free to copy these functions however they wish. What this means is that if your comparison object contains state, this state must be copied correctly so you may need to provide ...
2,141,643
2,141,741
Boost regexp - null-termination of search results
boost::regex re; re = "(\\d+)"; boost::cmatch matches; if (boost::regex_search("hello 123 world", matches, re)) { printf("Found %s\n", matches[1]); } Result: "Found 123 world". I just wanted the "123". Is this some problem with null-termination, or just misunderstanding how regex_search works?
You can't pass matches[1] (an object of type sub_match<T>) to printf like that. The fact that it gives any useful result at all is something you can't count on, since printf expects a char pointer. Instead use: cout << "Found " << matches[1] << endl; Or if you want to use printf: printf("Found %s\n", matches[1].str()....
2,141,748
2,141,901
Overloading Operators in C++, exporting and Importing then in VB.NET
Howdy all, I have a weird situation. I have a C++ code that overloads the +,-,* operators and exports them in a .DLL file. Now, I want to import those overloaded operators from within VB.NET code. So it should be like this: <DllImport("StructDLL.dll")> Public Shared Function Operator +(ByVal a1 As A, ByVal a2 As A) ...
You cannot make this work. The P/Invoke marshaller doesn't support functions that return structures.
2,141,749
2,141,771
What does ifstream::rdbuf() actually do?
I have the following code and it works pretty good (other than the fact that it's pretty slow, but I don't care much about that). It doesn't seem intuitive that this would write the entire contents of the infile to the outfile. // Returns 1 if failed and 0 if successful int WriteFileContentsToNewFile(string inFilename,...
Yes, it's specified in the standard and it's actually quite simple. rdbuf() just returns a pointer to the underlying basic_streambuf object for the given [io]stream object. basic_ostream<...> has an overload for operator<< for a pointer to basic_streambuf<...> which writes out the contents of the basic_streambuf<...>.
2,141,751
2,141,843
How to set a value in windows registry? (C++)
I want to edit key "HKEY_LOCAL_MACHINE\Software\company name\game name\settings\value" to "1" (DWORD) This is my code: HKEY hkey; DWORD dwDisposition; if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\company name\\game name\\settings"), 0, NULL, 0, 0, NULL, &hkey, &dwDisposition) == ERROR_SUCCESS){ DWORD dwTyp...
Always check the return value of API functions. You'll see that RegSetValueEx() returns 5, access denied. You didn't ask for write permission. Fix: if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\company name\\game name\\settings"), 0, NULL, 0, KEY_WRITE, NULL, &hkey, &dwDispositi...
2,141,848
2,141,878
How do I convert a "pointer to const TCHAR" to a "std::string"?
I have a class which returns a typed pointer to a "const TCHAR". I need to convert it to a std::string but I have not found a way to make this happen. Can anyone provide some insight on how to convert it?
Depending on your compiling settings, TCHAR is either a char or a WCHAR (or wchar_t). If you are using the multi byte character string setting, then your TCHAR is the same as a char. So you can just set your string to the TCHAR* returned. If you are using the unicode character string setting, then your TCHAR is a wi...
2,141,929
2,141,941
C++ algorithm for N! orderings
I have a list of N items and I am wondering how I can loop through the list to get every combination. There are no doubles, so I need to get all N! orderings. Extra memory is no problem, I'm trying to think of the simplest algorithm but I'm having trouble.
See std::next_permutation   
2,142,325
2,142,370
g++ compiler: optimization flag adds warning message
I noticed this interesting behaviour of the g++ compiler, if I add a -O3 flag to the compiler, I get otsu.cpp:220: warning: ‘x’ may be used uninitialized in this function However, when I do not use optimization and instead use a debug flag -g I got no warnings at all. Now, I trust the compiler more when the -g flag is...
That's expected. The optimizations cause a specific code analysis to run and that's how gcc finds the un-initialized variables. It's in the manual page: . . . these warnings depend on optimization http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
2,142,461
2,143,003
Good book for Monte Carlo methods in c++?
Can anybody recommend a good introduction book on Monte Carlo algorithms in c++? Preferably with applications to physics, and even more preferably, the kind of physics being quantum mechanics. Thanks!
You can have a look at Morten Hjorth-Jensen's Lecture Notes on Computational Physics (pdf file, 5.3 MB), University of Oslo (2009), chapters 8-11 (especially chapter 11, on Quantum Monte Carlo). However, you should make sure you are not trying to learn too many things at the same time (Monte Carlo, C++, quantum mechan...
2,142,611
2,142,728
Using pointer to base class as array parameter
I have 2 classes: class Base { public: virtual int Foo(int n); virtual void Goo() = 0; virtual ~Base() ; }; class Derived : public Base { public: int Add4Bytes; void Goo(); int Foo(int n); }; int Test(Base* b) { for (int i=0;i<5;++i) { b->Foo(i); ++b; ...
Arrays don't deal well with polymorphic types as contents due to object slicing. An array element has a fixed size, and if your derived objects have a larger size than the base then the array of base objects can't actually hold the derived objects. Even though the function parameter might be decaying into a pointer, t...
2,142,708
2,142,778
friend function in derived class with private inheritance
If a class Derived is inherited privately from a class Base and the Derived class has a friend function f(), so what members can f() access from Derived class and Base class. class Base { public: int a; protected: int b; private: int c; }; class Derived: private Base { void friend f() {} public...
'Friendship' grants access to the class that declares the friend - it's not transitive. To use a bad analogy - my friends are not necessarily my dad's friends. The C++ FAQ has a bit more detail: http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4
2,142,790
2,142,851
QT slot get Signaled twice
In QT4.5, I use a QTableWidget, and I have connected the signal QTableWidget::itemClicked() to a custom slot like this: connect(_table, SIGNAL(itemClicked(QTableWidgetItem*)), item, SLOT(sloItemClicked(QTableWidgetItem*))); I create such a connection for each row I add to the table. The problem is that the slot sloIte...
You should only create the connection once since the signal is a signal on the table and not on an individual QTableWidgetItem. When emitted it will give you the QTableWidgdetItem that you clicked on as the argument.
2,142,834
2,143,334
C++ specific patterns due to language design
It took me a long time to realize how important and subtle having variables that: 1) exist on the stack 2) have their destructors called when they fall out of scope are. These two things allow things like: A) RAII B) refcounted GC Interesting enough, (1) & (2) are not available in "lower" languages like C/Assembly; nor...
I really love trait classes. Not exactly specific of C++ (other languages as Scala have them), but it allows you to adapt objects, basically to specify a set of operations that a type should support. Imagine that you want a "hasher", in the sense of tr1::hash. hash is defined for some types, but not for others. How can...
2,142,906
2,143,218
Using C#/C++, is it possible to limit network traffic?
I'm developing a parental monitoring/tracking application that has a feature to lock down all internet activity. While disabling the network adapter would seem like a simple solution, the application must have the ability to turn the internet back on remotely -- so the network needs to remain enabled, to a certain lim...
You need to inject a custom layer into the IP stack, using Windows Filtering Platform. This SDK targets specifically parental control programs and such. Needless to say, as any kernel module, it has to be developed in C and you must have expert knowledge of Windows internals: The Windows Filtering Platform API is de...
2,142,965
2,143,009
C++ "move from" container
In C++11, we can get an efficiency boost by using std::move when we want to move (destructively copy) values into a container: SomeExpensiveType x = /* ... */; vec.push_back(std::move(x)); But I can't find anything going the other way. What I mean is something like this: SomeExpensiveType x = vec.back(); // copy! vec....
I might be total wrong here, but isn't what you want just SomeExpensiveType x = std::move( vec.back() ); vec.pop_back(); Assuming SomeExpensiveType has a move constructor. (and obviously true for your case)
2,143,020
2,143,734
Why can't I inherit from int in C++?
I'd love to be able to do this: class myInt : public int { }; Why can't I? Why would I want to? Stronger typing. For example, I could define two classes intA and intB, which let me do intA + intA or intB + intB, but not intA + intB. "Ints aren't classes." So what? "Ints don't have any member data." Yes they do, they ...
Neil's comment is pretty accurate. Bjarne mentioned considering and rejecting this exact possibility1: The initializer syntax used to be illegal for built-in types. To allow it, I introduced the notion that built-in types have constructors and destructors. For example: int a(1); // pre-2.1 error, now initia...
2,143,022
2,143,038
How to correctly initialize member variable of template type?
suggest i have a template function like following: template<class T> void doSomething() { T a; // a is correctly initialized if T is a class with a default constructor ... }; But variable a leaves uninitialized, if T is a primitive type. I can write T a(0), but this doesn't work if T is a class. Is there a way...
Like so: T a{}; Pre-C++11, this was the simplest approximation: T a = T(); But it requires T be copyable (though the copy is certainly going to be elided).
2,143,240
2,143,752
opengl: glFlush() vs. glFinish()
I'm having trouble distinguishing the practical difference between calling glFlush() and glFinish(). The docs say that glFlush() and glFinish() will push all buffered operations to OpenGL so that one can be assured they will all be executed, the difference being that glFlush() returns immediately where as glFinish() bl...
Mind that these commands exist since the early days of OpenGL. glFlush ensures that previous OpenGL commands must complete in finite time (OpenGL 2.1 specs, page 245). If you draw directly to the front buffer, this shall ensure that the OpenGL drivers starts drawing without too much delay. You could think of a complex ...
2,143,327
2,143,584
C++: Template Parameter Cyclic Dependency
This is more a best practice question than a language question in itself, since I already have a working solution to what seems to be a common stumbling block in C++. I'm dealing with a typical cyclic dependency issue in template parameter substitutions. I have the following pair of classes: template<class X> class A {...
Since a template's type names all its parameters, you can't have an endless loop of parameterization. You are probably (certainly) just trying to send information in opposite directions at the same time. There's no problem with that, but you can't encapsulate the information in the classes that provide implementation. ...
2,143,352
2,143,358
Add my own compiler warning
When using sprintf, the compiler warns me that the function is deprecated. How can I show my own compiler warning?
In Visual Studio, #pragma message ("Warning goes here") On a side note, if you want to suppress such warnings, find the compiler warning ID (for the deprecated warning, it's C4996) and insert this line: #pragma warning( disable : 4996)
2,143,394
2,144,095
Operator== in derived class never gets called
Can someone please put me out of my misery with this? I'm trying to figure out why a derived operator== never gets called in a loop. To simplify the example, here's my Base and Derived class: class Base { // ... snipped bool operator==( const Base& other ) const { return name_ == other.name_; } }; class Derived : pu...
There are two ways to fix this. First solution. I would suggest adding some extra type logic to the loop, so you know when you have a Base and when you have a Derived. If you're really only dealing with Derived objects, use list<Derived*> coll; otherwise put a dynamic_cast somewhere. Second solution. Put the same kind...
2,143,482
2,143,518
Network connection setup in constructor: good or bad?
I'm working on a class that handles interaction with a remote process that may or may not be available; indeed in most cases it won't be. If it's not, an object of that class has no purpose in life and needs to go away. Is it less ugly to: Handle connection setup in the constructor, throwing an exception if the proce...
I consider it bad to do a blocking connect() in a constructor, because the blocking nature is not something one typically expects from constructing an object. So, users of your class may be confused by this functionality. As for exceptions, I think it is generally best (but also the most work) to derive a new class fr...
2,143,656
2,143,744
Visual Studio 2010 C++ compiler - Get current line number when compiling
i have a question about how to get the current line number while compiling of the VS C++ compiler, IF its possible of course. I know its possible to use the LINE Macro from the preprocessor, but the results i get are not correct (well, at least not what i want). Please tell me its possible :) Thanks in advance edit: I ...
Ok...to explain a bit better, as I think you have misunderstood the implications of the __LINE__ macro... Consider three source files: /* Source1.c */ ...list of headers & functions .... if (!(fp = fopen("foo.blah", "r"))){ fprintf(stderr, "Error in %s @ line: %d: Could not open foo.blah\n", __FILE__, __LINE__); } ...
2,143,714
2,143,727
What is the best way to deal with co-dependent classes in C++?
Say I have a class foo with an object of class bar as a member class foo { bar m_bar; }; Now suppose bar needs to keep track of the foo that owns it class bar { foo * m_pfoo; } The two classes reference each other and without a forward declaration, will not compile. So adding this line before foo's declaratio...
You need to move all of the member access out of the header, and into your source files. This way, you can forward declare your classes in the header, and define them in foo: // foo.h class bar; class foo { bar * m_pbar; } // bar.h class foo; class bar { foo * parent; } That will allow you to work - you just...
2,143,787
2,143,841
What is copy elision and how does it optimize the copy-and-swap idiom?
I was reading Copy and Swap. I tried reading some links on Copy Elision but could not figure out properly what it meant. Can somebody please explain what this optimization is, and especially what is mean by the following text This is not just a matter of convenience but in fact an optimization. If the parameter (s) bi...
The copy constructor exists to make copies. In theory when you write a line like: CLASS c(foo()); The compiler would have to call the copy constructor to copy the return of foo() into c. Copy elision is a technique to skip calling the copy constructor so as not to pay for the overhead. For example, the compiler can a...
2,143,906
2,143,953
C/C++: Calling function with no arguments with function which returns nothing
Why isn't it possible to call a function which takes no arguments with a function call as argument which does not return any value (which IMHO is equivalent to calling a function which takes no arguments with no arguments). For example: void foo(void) {...} void bar(void) {...} foo(bar()) Don't get me wrong, I know v...
I'm not convinced that any of the reasons I've heard are good ones. See, in C++, you can return a void function's result: void foo() { // ... } void bar() { // ... return foo(); } Yes, it's exactly the same as: foo(); return; but is much more consistent with generic programming, so that you can make a fo...
2,144,012
2,434,989
Explicit Type Conversion and Multiple Simple Type Specifiers
To value initialize an object of type T, one would do something along the lines of one of the following: T x = T(); T x((T())); My question concerns types specified by a combination of simple type specifiers, e.g., unsigned int: unsigned int x = unsigned int(); unsigned int x((unsigned int())); Visual C++ 2008 and In...
I posted this question to comp.lang.c++.moderated. Daniel Krügler of the C++ standards committee agreed with the interpretation that unsigned int is a combination of simple type specifiers, and is not itself a simple type specifier. Concerning the caption of table 7 referenced by Jerry Coffin, Krügler says: I agree th...
2,144,144
2,144,160
Problem with re-using a stringstream object
I'm trying to use safe practices in handling input with numbers only in C++, so I use a stringstream object as so: #include <iostream> #include <string> #include <sstream> using namespace std; int main() { int first, second; string input; stringstream sstream; cout << "First integer: "; getline(c...
Use sstream.clear(); after sstream >> first;.
2,144,219
2,146,301
How can I determine why a call to IXMLDOMDocument::load() fails?
I am trying to debug what appears to be an XML parsing issue in my code. I have isolated it down to the following code snippet: HRESULT CXmlDocument::Load(IStream* Stream) { CComVariant xmlSource(static_cast<IUnknown*>(Stream)); VARIANT_BOOL isSuccessful; * HRESULT hr = m_pXmlDoc->load(xmlSource, &isSuccessf...
The following code will fetch the specific parser error from the DOM and it's location in the source XML. CComPtr<IXMLDOMParseError> pError; CComBSTR sReason, sSource; long nLine = 0, nColumn = 0; m_pXmlDoc->get_parseError(&pError); if(pError) { pError->get_reason(&sReason); pError->get_srcText(&sSource); ...
2,144,282
2,144,607
Redirect std*** from C++ to Java for Logging
I have a C++ application and a Java application that need to log messages in the same way. My Java application uses Apache Commons Logging, backed by a Log4j configuration. I need a single log4j configuration so I can change my logging preferences in one location. In my C++ application, I have captured all calls to pri...
In addition to the performance cost, anything except option 3 is also horribly complicated (*). Also, I am not sure that there is a Java library that reads an InputStream and transforms it into Commons Logging calls. Even if there is, in order to be able to control filtering completely with the Java-side configuration,...
2,144,290
2,144,356
how to use blitz_0.9
I down load blitz_0.9,I can build it in vs2008 and get blitzd.lib and blitz.lib but how can i get blitz.dll who have used it give me some advice thank you.
Are you sure you didn't just compile the static version of the library? If so no .dll will be produced. Perhaps you can show the commands you used to build the library.
2,144,454
2,144,605
Detour to get a Global Pointer?
I need to get the protocol version of an application, and I don't know too much about the inner workings of detouring. I usually use a detour class written by a friend of mine (Not windows detour, as this works on win/linux) but im wondering if anyone can give me some insight on how to retrieve the value of a global po...
if it's already a compiled binary. How about extracting the string using string pattern match? For example you can read in the file char by char and search for the pattern: Protocol version %i\nExe version %s (%s)
2,144,677
2,157,258
Qt: How to show icon when item selected
I have a QListWidget containing items which have icons and when the items are selected the icon is just highlighted out. Is there a way to prevent this? I can't use stylesheets because it's for an embedded application and including them takes up too much space. thanks
Certainly, drawing on a black-and-white screen presents its challenges. It sounds like you just want to change the appearance of the interface, not any functionality. If this is the case, a QItemDelegate-derived class (or QStyledItemDelegate) is almost certainly what you want. In particular, the drawDecoration functi...
2,144,698
2,144,737
Common Uses For Pointers?
I'm a programming student with two classes in C#, but I'm just taking my first class in C++, and thus I'm being exposed to pointers. I know how they work, and the proper way to use them, but I wondered about some of the ways that professional programmers use pointers in their programs. So how do you use pointers? Or d...
Any time you'd use a reference in C#. A "reference" is just a pointer with fancy safety airbags around it. I use pointers about once every six lines in the C++ code that I write. Off the top of my head, these are the most common uses: When I need to dynamically create an object whose lifetime exceeds the scope in whic...
2,144,805
2,144,810
After hooking hook procedure is called infinitely
I have hooked WM_SETFOCUS message by calling API hhookCallWndProc = SetWindowsHookEx(WH_CALLWNDPROC, HookCallWndProc, hInst, threadID); Hook Procedure is extern "C" LRESULT _declspec(dllexport) __stdcall CALLBACK HookCallWndProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HC_ACTION) { ...
Quick guess - doesn't closing a message box force a re-focus of the control and therefore call your function again?
2,144,814
2,146,148
Questions on usages of shared_ptr - C++
I have few questions on the best practices of using shared_ptr. Question 1 Is copying shared_ptr cheap? Or do I need to pass it as reference to my own helper functions and return as value? Something like, void init_fields(boost::shared_ptr<foo>& /*p_foo*/); void init_other_fields(boost::shared_ptr<foo>& /*p_foo*/); bo...
Most of the questions have been answered, but I disagree that a shared_ptr copy is cheap. A copy has different semantics from a pass-by-reference. It will modify the reference count, which will trigger an atomic increment in the best case and a lock in the worst case. You must decide what semantics you need and then ...
2,145,030
2,145,824
Are all temporaries rvalues in C++?
I have been coding in C++ for past few years. But there is one question that I have not been able to figure out. I want to ask, are all temporaries in C++, rvalues? If no, can anyone provide me an example where temporary produced in the code is an lvalue?
No. The C++ language specification never makes such a straightforward assertion as the one you are asking about. It doesn't say anywhere in the language standard that "all temporary objects are rvalues". Moreover, the question itself is a bit of misnomer, since the property of being an rvalue in the C++ language is not...
2,145,147
2,145,555
Why catch an exception as reference-to-const?
I've heard and read many times that it is better to catch an exception as reference-to-const rather than as reference. Why is: try { // stuff } catch (const std::exception& e) { // stuff } better than: try { // stuff } catch (std::exception& e) { // stuff }
You need: a reference so you can access the exception polymorphically a const to increase performance, and tell the compiler you're not going to modify the object The latter is not as much important as the former, but the only real reason to drop const would be to signal that you want to do changes to the exception (...
2,145,331
2,145,342
C++: Undefined reference to instance in Singleton class
I'm currently trying to implement a factory as a singleton. I practically used the textbook example of the Singleton pattern. Here's the .h file: namespace oxygen{ class ImpFactory{ public: static boost::shared_ptr<ImpFactory> GetInstance(); private: static boost::shared_ptr<ImpFactory> mInstance; }; and he...
You must define the static instance, not just declare it. The definition creates the actual object you refer to. In your cpp file, add the line: boost::shared_ptr<ImpFactory> ImpFactory::mInstance;
2,145,407
2,146,866
The best way of developing on Symbian
I am going to develop on Symbian (S60), and I know there are some ways to develop on this platfrom: Symbian C++, Java ME, Qt,OVI etc. I need an overall brief guide on all the ways and I have a few questions: What's the difference between Symbian C++ and Jave ME when developing? If Java ME can run on Symbian ,why we n...
The best way of developing on Symbian OS depends on what you already know, your budget and what you want to accomplish. What's the difference between Symbian C++ and Java ME when developing? Well, you wouldn't use the same tools, it's not the same runtime, it's not the same language. Typically, one would use C++ when...
2,145,767
2,145,783
Why can't reference to child Class object refer to the parent Class object?
I was explaining OOP to my friend. I was unable to answer this question. I just escaped by saying, since OOP depicts the real world. In real world, parents can accommodate children but children cannot accommodate parents. same is the case in OOP. class Parent { int prop1; int prop2; } class Child : Parent // class...
Exactly because aChild is a superset of aParent's abilities. You can write: class Fox : Animal Because each Fox is an Animal. But the other way is not always true (not every Animal is a Fox). Also it seems that you have your OOP mixed up. This is not a Parent-Child relationship, because there's no composition/trees in...
2,145,838
2,145,875
Insert a pair of object into a map
I'm trying to insert some pair value into a map. May map is composed by an object and a vector of another object. i don't know why but the only way to make the code to compile is to declare the first object like a pointer. But in this way when I insert some object, only the first pair is put into the map. My map is thi...
You need to supply a comparator for prmEdge. My guess is that it uses the default comparator for map, e.g. comparing the address of the key -- which is always the same because e is local. Objects that serve as Keys in the map need to be ordered, so you either need to supply a operator for comparing edges, or a comparat...
2,145,931
2,145,964
Why is "operator bool()" invoked when I cast to "long"?
I have the following class: class MyClass { public: MyClass( char* what ) : controlled( what ) {} ~MyClass() { delete[] controlled; } operator char*() const { return controlled; } operator void*() const { return controlled; } operator bool() const { return controlled != 0; } private: char* controlled...
It's one of the known pitfalls of using operator bool, that is a aftershock of C inheritance. You'd definitively benefit from reading about the Safe Bool Idiom. In general, you didn't provide any other matchable casting operator, and bool (unfortunately) is treated as a good source for arithmetic casting.
2,145,996
2,146,058
Friend mixin template?
Let's say I have two classes Foo and Bar, and I want to make Foo friends with Bar without changing Foo. Here's my attempt: class Foo { public: Foo(){} private: void privateFunction(){} }; template <class friendly, class newFriend> class friends : public friendly { private: friend ...
It doesn't work, because friends has no access to privateFunction anyway, because it's private (descendant classes have no access to private fields anyway). If you would declare privateFunction as protected, it would work. Here's a nice paper about Mixins in C++. (PDF link)
2,146,106
2,146,199
How can I make sure a boost::optional<T> object is initialized in release-build?
When trying to get the value of a boost::optional object, BOOST_ASSERT is used to make sure the object is indeed initialized. But what I would like when dereferencing an uninitialized optional is for an exception to be thrown - is there any way to get this behaviour in a release build? If not, is there any other simil...
Unfortunately optional doesn't give such an option. The whole point of optional is to be able to check if the value is present by using the overloaded bool operator. Optional was designed to allow NOT to throw exceptions in functions, but return a success/failure with the value instead. Maybe you should return a value...
2,146,191
2,146,548
Obtaining local IP address using getaddrinfo() C function?
I'm trying to obtain my local (not the external) IP address using the getaddrinfo() function, but I saw the examples provided here, and they where too complex for my needs. Also saw other posts and most of them really wanted to get the external IP, not the local one. Could anyone provide a link to a simple example (or ...
getaddrinfo() isn't for obtaining your local IP address - it's for looking up names and/or services to socket addresses. To obtain the local IP address(es), the function you want is getifaddrs() - here's a minimal example: #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <...
2,146,202
2,146,212
Difference between pointer in C++ and reference type in C#
In C++ a pointer is a pointer to an address of memory where another variable is stored and in C# a reference is some how same. What is the difference between these two?
In C# the reference type will be automatically garbage collected when no longer needed.
2,146,207
2,146,250
What is the significance of a .h file?
I know that .h file is supposed to have: class declarations, function prototypes, and extern variables (for global variables) But is there some significance of making it a .h file? I tried renaming my .h file to a .c file and it still works. We can name our file to be anything, but we choose to name it as a .h file....
The use of .h to name header files is just a convention. You will also see (probably on Unix-like platforms): .hpp (the Boost library uses these) .hxx (looks like h++ with the + signs tilted - cute, huh?) .H (Unix is case sensitive so you can distinguish these from .h files) Personally, I'd strongly advise st...
2,146,589
2,163,606
open source language recognition library?
I'm searching for a lib which can recognize the human language of a .txt document I already found this page but im more interested in source code which I can use offline some language which would be great to support english, french, german programming language which would be best c/c++, php, JS is also ok Any hints for...
Have a look a this library: http://software.wise-guys.nl/libtextcat/
2,146,708
2,146,723
How to define /declare a class intance in a .hpp / .cpp file?
I'm pretty sure that this question is very noob but I'm not used to C++. I have a .hpp for class definition and a .cpp for class implementation. I have some private instances on the class, for example: class Test { Test(void); private: SomeClass anInstance; }; To create the instance and call the const...
No, you need an initialisation list: Test::Test(void) : anInstance( parameters) { } This will work well for fixed parameters, like "foobar" or 42, but if you need to pass variable parameters in, you also need to change the Test constructor definition (and the declaration in the header). For example, iif it takes an in...
2,146,763
2,146,824
Using continue in a switch statement
I want to jump from the middle of a switch statement, to the loop statement in the following code: while (something = get_something()) { switch (something) { case A: case B: break; default: // get another something and try again continue; } // do something for a handl...
It's fine, the continue statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements): while (something = get_something()) { if (something == A || something == B) do_something(); } But if you expect break to exit the loop, as your comment suggest (it always ...
2,146,792
2,146,804
How do you generate random strings in C++?
I am looking for methods to generate random strings in C++.Here is my code: string randomStrGen(int length) { static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; string result; result.resize(length); srand(time(NULL)); for (int i = 0; i < length; i++) r...
Don't call srand() on each function call - only call it once at first function call or program startup. You migh want to have a flag indicating whethersrand() has already been called. The sugested method is good except that you misuse srand() and get predictably bad results.
2,146,901
2,147,812
Why can I not call my class's constructor from an instance of that class in C++?
When can an object of a class call the destructor of that class, as if it's a regular function? Why can't it call the constructor of the same class, as one of its regular functions? Why does the compiler stops us from doing this? For example: class c { public: void add() ; c(); ~c() ; }; void main() { c objC...
By definition, a constructor is only called once, when the object is created. If you have access to an object, then it must have been created, so you're not allowed to call the constructor again - this is the reason why explicit constructor calls are not allowed. Similarly, destructors must only be called once, when th...
2,147,471
2,147,703
C++ forward class declaration generator
Is there a tool that would go through a list of files and would spit out a header file with forward declarations of classes it encounters? Ideally, I would like to integrate it into Visual C++'s build process.
Not that I know of. But I guess that all that you want are class names, so grep, awk or something like that would do the job.
2,147,600
2,147,686
Are there any downsides with using make_shared to create a shared_ptr
Are there any downsides with using make_shared<T>() instead of using shared_ptr<T>(new T). Boost documentation states There have been repeated requests from users for a factory function that creates an object of a given type and returns a shared_ptr to it. Besides convenience and style, such a function is a...
I know of at least two. You must be in control of the allocation. Not a big one really, but some older api's like to return pointers that you must delete. No custom deleter. I don't know why this isn't supported, but it isn't. That means your shared pointers have to use a vanilla deleter. Pretty weak points. so tr...
2,147,722
2,147,886
How to define a general member function pointer
I have created a Timer class that must call a callback method when the timer has expired. Currently I have it working with normal function pointers (they are declared as void (*)(void), when the Elapsed event happens the function pointer is called. Is possible to do the same thing with a member function that has also ...
Dependencies, dependencies... yeah, sure boost is nice, so is mem_fn, but you don't need them. However, the syntax of calling member functions is evil, so a little template magic helps: class Callback { public: void operator()() { call(); }; virtual void call() = 0; }; class BasicCallback : ...
2,148,141
2,148,261
Why does G++ tell me "Stack" is not declared in this scope?
I created the following two C++ files: Stack.cpp #include<iostream> using namespace std; const int MaxStack = 10000; const char EmptyFlag = '\0'; class Stack { char items[MaxStack]; int top; public: enum { FullStack = MaxStack, EmptyStack = -1 }; enum { False = 0, True = 1}; // methods void ...
Your Stack is declared in Stack.cpp, as you said. You are trying to use it in StackTest.cpp. Your Stack is not declared in StackTest.cpp. You can't use it there. This is what the compiler is telling you. You have to define classes in all translation units (.cpp files), in which you are planning to be using them. Moreov...
2,148,185
2,148,360
Run Linux commands from Qt4
How can I run command-line programs under Linux from Qt4? And of course I want to obtain the output in some way I can use. I'd use it for an ls | grep, but it's good to know for any future issues.
QProcess p; p.start( /* whatever your command is, see the doc for param types */ ); p.waitForFinished(-1); QString p_stdout = p.readAllStandardOutput(); QString p_stderr = p.readAllStandardError();
2,148,611
2,269,267
generating library version and build version
I have a library that I build and release to the customers. The platform is linux. I was wondering if there is any way to generate library version and build version as part of the build? This will help me to co-relate any issues reported by the different customers with a particular version of the build.
There are 2 options: Embed the version information into the name of the library, e.g. libmy.so.1.2, which should be soft-linked into libmy.so in your installation to be able to resolve it at run-time. Modify your build tools to accommodate this. This is a common approach, but not really convenient for build labels. Y...
2,148,618
2,148,708
Is it possible to override a Java implementation of the Random class?
Using Windows Detours in C++, I've seen that it is possible to trampoline function calls so that you may intercept windows base functionality and return custom resultsets, without modifying the original function call. I was wondering if there is any way to override a Java Randomization call so that I may implement my...
If you are responsible for instantiating a java.util.Random object, then you can subclass java.util.Random and instantiate your own class instead. If some other code, that you cannot change, is responsible for the instantiation, then you obviously cannot use your own subclass. I expect this is not an option in your cas...
2,148,769
2,148,843
typedef and containers of const pointers
The following line of code compiles just fine and behaves: list<const int *> int_pointers; // (1) The following two lines do not: typedef int * IntPtr; list<const IntPtr> int_pointers; // (2) I get the exact same compile errors for list<int * const> int_pointers; // (3) I'm well aware that the last line is not le...
Short answer: is a list of pointers to constant ints. is a list of constant pointers to ints. is the same as 2. const (and volatile) should naturally appear after the type they qualify. When you write it before, the compiler automatically rewrites it internally: const int * becomes int const * which is a pointer to...
2,148,777
2,159,991
Boost::Python, static factories, and inheritance
So I may have a rather unique use case here, but I'm thinking it should work- But it's not working correctly. Basically, I have a class that uses a static factory method ( create ) that returns a shared_ptr to the newly created instance of the class. This class also has a virtual function that I'd like to override from...
I ended up rethinking my design using intrusive_ptrs. There was a little more work to be done with the wrappers than using shared_ptr, but it worked out fairly well. Thanks to everyone for their time.