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 Radians class is that it adds code and makes the program slower. Is there a better way to do this?
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 converted to radians before being passed to the function. That will possibly slow things down a bit, but it arranges it so you can change what units a function wants without having to go back and edit a whole ton of code. And, when you finally do want to go and edit all the code, you can temporarily fix it so the conversion doesn't work and let the compiler find it for you. Being able to make the compiler enforce constraints like this for you with no runtime penalty and possibly even write all the conversion code for you (at a very tiny runtime penalty) is one of the really neat things about C++ and makes it worth the added complexity over C. Here is a really simple version of what this class might look like if you hand coded it: #include <cmath> // This class is tiny enough because it has no virtual functions and only one // data member that it's likely more efficient to pass by value than by // reference. class Radians { public: // If you don't put in explicit, the compiler will automatically convert a // float to a Radians for you and undo all of the hard work you did to make // sure callers express their intentions. explicit Radians(float radians) : value_(radians) {} float getValue() const { return value_; } void setValue(float radians) { value_ = radians; } float asDegrees() const { return value_ * 180 / M_PI; } // This allows you to say Radians r = Radians::fromDegrees(something); static Radians fromDegrees(float degrees) { return Radians(degrees * M_PI / 180); } private: float value_; }; Notice how all of the functions are declared in the class body. This makes them all implicitly have the inline keyword. A good compiler will optimize all of those functions out of existence. Of course, the conversion functions will generate the code to do the conversion, but otherwise it'll be the same as having a bare float.
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 get passed through foo. I do want to store pointers to them, but I'm confused about the syntax of how to do that.
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 is appreciated. Thanks.
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 takes an explicit timeout value.
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, HistoParameter*> hp; hp[std::string("ph_pt")] = new HistoParameter(100,0,22000); hp[std::string("ph_eta")] = new HistoParameter(100,-3,3); // ... return hp[var_name]; } My struct is very light, but image it can be heavy. The prolem is that every time I call this function it create a lot of HistoParameter objects, maybe a switch case is more efficient. First question: I'm creating garbage? Second solution: bool first_time = true; HistoParameter* variable_to_parameter(char* var_name) { static std::map<const std::string, HistoParameter*> hp; if (first_time) { hp[std::string("ph_pt")] = new HistoParameter(100,0,22000); hp[std::string("ph_eta")] = new HistoParameter(100,-3,3); // ... } first_time = false; return hp[var_name]; is it ok? Better solution?
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 well. Second, I would not use pointers and/or dynamic allocation for the HistoParameter values. At one int and two floats, there's simply no reason to do so. If you're really passing them around so much that copying became a problem, you'd probably be better off using some sort of smart pointer class instead of a raw pointer -- the latter is more difficult to use and much more difficult to make exception safe. Third, I'd consider whether it's worthwhile to make variable_to_parameter into a functor instead of a function. In this case, you'd initialize the map in the ctor, so you wouldn't have to check whether it was initialized every time operator() was invoked. You can also combine the two, by have a static map in the functor. The ctor initializes it if it doesn't exist, and operator() just does a lookup. Finally, I'd note that map::operator[] is primarily useful for inserting items -- it creates an item with the specified key if it doesn't exist, but when you're looking for an item, you usually don't want to create an item. For this, you're generally better off using map.find() instead.
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 this code using g++ (Debian 4.3.2-1.1) 4.3.2 prints 0x7FFFF470EE90 which is 0b11111111111111111110100011100001110111010010000. Due to the alignment I expect the last 7 bits of the variable's address to be zero. Do I make an error in reasoning here? What's going on? Thanks in advance, Sebastian
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 not really capable of doing so on Windows.
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 have only problems when I compile it, I don't know why. This is the code: static const unsigned char cycles_table[256] = { /* 8080's Cycles Table */ /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /*0*/ 4, 10, 7, 5, 5, 5, 7, 4, 0, 10, 7, 5, 5, 5, 7, 4, /*1*/ 0, 10, 7, 5, 5, 5, 7, 4, 0, 10, 7, 5, 5, 5, 7, 4, /*2*/ 0, 10, 16, 5, 5, 5, 7, 4, 0, 10, 16, 5, 5, 5, 7, 4, /*3*/ 0, 10, 13, 5, 10, 10, 10, 4, 0, 10, 13, 5, 5, 5, 7, 4, /*4*/ 5, 5, 5, 5, 5, 5, 7, 5, 5, 5, 5, 5, 5, 5, 7, 5, /*5*/ 5, 5, 5, 5, 5, 5, 7, 5, 5, 5, 5, 5, 5, 5, 7, 5, /*6*/ 5, 5, 5, 5, 5, 5, 7, 5, 5, 5, 5, 5, 5, 5, 7, 5, /*7*/ 7, 7, 7, 7, 7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 7, 5, /*8*/ 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, /*9*/ 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, /*A*/ 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, /*B*/ 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, /*C*/ 5, 10, 10, 10, 11, 11, 7, 11, 5, 10, 10, 0, 11, 17, 7, 11, /*D*/ 5, 10, 10, 10, 11, 11, 7, 11, 5, 0, 10, 10, 11, 0, 7, 11, /*E*/ 5, 10, 10, 18, 11, 11, 7, 11, 5, 5, 10, 4, 11, 0, 7, 11, /*F*/ 5, 10, 10, 4, 11, 11, 7, 11, 5, 5, 10, 4, 11, 0, 7, 11 }; g++ takes me this error: 8080.h:521: error: invalid in-class initialization of static data member of non- integral type `const unsigned char[256]' This array is in a class called i8080.
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 in the corresponding source file, place what you have: const unsigned char i8080::cycles_table[256] = // ... What this does is say (in the definition), "Hey, there's gonna be this array." and in the source file, "Hey, here's that array."
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))) CXXFLAGS = $(OPT_FLAGS) -MMD -MF $(BUILD_DIR)/$*.d -D_LINUX -DNDEBUG -pipe DCXXFLAGS = $(DEBUG_FLAGS) -MMD -MF $(BUILD_DIR)/$*.d -v -D_LINUX -D_DEBUG -pipe OBJECTS := $(patsubst %.cpp, $(BUILD_DIR)/Release/%.o, $(notdir $(SOURCES))) DOBJECTS := $(patsubst %.cpp, $(BUILD_DIR)/Debug/%.o, $(notdir $(SOURCES))) $(OBJECTS): $(BUILD_DIR)/Release/%.o: %.cpp +@[ -d $(dir $@) ] || mkdir -p $(dir $@) $(CPP) $(INCLUDE) $(CXXFLAGS) $(DEFINES) -o $@ -c $< Its a little complicated but what it does in C is build all the %.c files defined in SOURCES and put the object files in BUILD_DIR. It works great in c, but this does not work with cpp files. I get make: *** No rule to make target `blue.cpp', needed by `build/Release/blue.o'. Stop. Its like VPATH is not working at all. I tried vpath %.cpp src/elements but that does not work either. Amazingly enough, renaming blue.cpp to blue.c and editing the makefile back to the %.c usage does work, it compiles just fine. Am I going crazy here?
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 generation scheme developed from http://mad-scientist.net/make/autodep.html and amazingly enough that was breaking make. Trouble occurred in with this line -include $(patsubst %.c, $(BUILD_DIR)/%.d, $(notdir $(SOURCES))) I did not change that to %.cpp and for some reason trying to include blue.cpp caused make to not search for it using vpath when it tried to resolve $(OBJECTS): $(BUILD_DIR)/Release/%.o: %.cpp So the solution was just to port the makefile correctly, doh!
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 this: http://httpd.apache.org/docs/2.0/mod/mod_so.html#creating it looks like it is just a naming convention - "Apache still loads .dlls..."
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 map? EDIT: Another point that came into my mind: of course using a map will force the compiler not to inline functions, but my inefficient approach didn't have any overhead generated by the necessity of function calls, it just executes code. So I wonder if the overhead generated by the function call will be any better than having an if..else chain.. otherwise I could minimize the number of comparisons by checking a character at runtime (will be longer but faster).
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) { auto iter = m.find(pFunction); if (iter == m.end()) { // not found } (*iter->second)(); } Note that the ScriptFunction type could be generalized to std::function</* whatever*/> so you can support any callable thing, not just exactly function pointers.
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 this isn't correct, but I am having some trouble getting it right. I want to get the elements 96 through 100 in array1 and put them into array2 but I don't want to copy the arrays. I just want array2 to start at the 96 element such that array1[96] and array2[0] would be pointing to the same location.
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 provide detailed explanation? Is it something related to name look-up? Btw, on Solaris, SunStudio12 it doesn't compile: error : formal argument x of type const std::pair<A*, A*> & in call to std::vector<std::pair<A*,A*> >::push_back(const std::pair<A*, A*> & ) is being passed std::pair<B*, B*>
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 callers? Consider Foo.h: class Foo { int bar() { return 1; } }; Foo::bar may be inlined or not in library foo.so. If another piece of code includes Foo.h does it always create its own copy of Foo::bar, whether inlined or not?
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 otherwise do. You can still take the address of an inline function, or equivalently, as you mention, export it. For those uses, the compiler simply treats it as non-inline and uses a One Definition Rule (the rule which says the user can't apply two definitions to the same function, class, etc) to "ensure" the function is defined once and only one copy is exported. Normally you are only allowed to have one definition among all sources; an inline function must have one definition which is repeated exactly in each source it is used. Here is what the standard has to say about inline extern functions (7.1.2/4): An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2). [Note: a call to the inline function may be encountered before its defi- nition appears in the translation unit. ] If a function with external linkage is declared inline in one transla- tion unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. An inline function with external linkage shall have the same address in all translation units. A static local variable in an extern inline function always refers to the same object. A string literal in an extern inline function is the same object in different translation units.
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 "messagehandler.h" #include "persist.h" class PersistMessageHandler : public MessageHandler { private: PersistHandle ph; size_t count; InternalCheck(); public: PersistMessageHandler(int someParam); virtual ~PersistMessageHandler (); virtual void HandleMessage(Message *msg): }; PersistMessageHandler::PersistMessageHandler(int someParam) { ph.Initialize(); } ... rest of implementation. MessageHandler *CreatePersistMessageHandler(int someParam) { return new PersistMessageHandler(someParam); } The reasoning here is to hide the PersistMessageHandler. Clients don't need to include a header for the PersistMessageHandler class, with all the includes and types the implementation might need, and to more cleanly seperate the interface and implementation. . It'll always be dynamically allocated anyway, All PersistMessageHandler users will just call CreatePersistMessageHandler(..); directly or indirectly get one from a factory. But. I've not seen this approach used much elsewhere. Is the above good practice ? Are there other/better alternatives for simple cases ?
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 a char* to prevent future bugs like this cropping up? std::string gets round this problem by not providing a char operator overload but, ideally, I'd like to keep the overload but prevent that delete from working.
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 it would somehow be selected will be a compile-time error. The intended ambiguity occurs before overload resolution - the private only serves to catch the exceedingly rare cases where the volatile overload would be selected somehow.
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 find the corresponding result from theMap (obviously 12958). Any nice and fast method of doing this, instead of your run-of-the-mill for loop? Other data structure suggestions are also welcome, but the map should be easy to write in the source by hand. The values in both sets are in the range of 0 to 2^16, and there are only about 130 pairs. What I also am after is a very simple way of statically initializing the data.
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 necessariily the fastest though. Both the binary search and the hashmap solutions suggested by others may (but not will) out-perform it. This probably won't matter for most applications, however.
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 like to rename python25.lib/.dll to something like gpython25.lib/.dll and link with them. This is to be sure to link with THIS python dll and not another python25.dll from another installed application, independently from the PATH search order. Is there a way to do that? Thanks -David
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 can quickly see what you're comparing against or is there more to it?
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 of Message class. I have implemented the function sendMessage as follows: void MyMessageBox::sendMessage(Message *msg, User *recvr) { Message &msgRef = *msg; recvr->dataMsgBox->dataMessageList.push_back(msgRef); } When I compile this code, I get the following error: undefined reference to `vtable for Message'. Please help me out to solve this issue. Thanks, Rakesh.
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 msgRef code entirely. Also, as a matter of style, it's a bad idea to chain lots of -> operators together. It's better to implement a method on User in this case that adds a Message to its own list and call that.
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: Build-Depends: ... libboost-dev (>=1.35), libboost-date-time-dev (>=1.35), ... but it seems that the 1.35 is hardcoded into the package names. i.e. libbost1.35-dev is a different package from libboost1.38m not just a different version of the same package. Is my understanding correct here? I can understand hardcoding major version numbers into the package name (if the new version's ABI breaks backward compatibility). Is there a way to write a Debian control file which allows a package to be depend on having a particular version of libboost or higher? Thanks, Chris.
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.org/doc/debian-policy/ch-relationships.html
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 would be great if you could also explain where to use each of those options.
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 need to pass by reference. (Use the previous rules to determine whether to pass by const reference or not.) Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional (boost::optional for older std libs), and aliasing is done fine by reference. C++11's move semantics make passing and returning by value much more attractive even for complex objects. Rules of thumb for C++03: Pass arguments by const reference, except when they are to be changed inside the function and such changes should be reflected outside, in which case you pass by non-const reference the function should be callable without any argument, in which case you pass by pointer, so that users can pass NULL/0/nullptr instead; apply the previous rule to determine whether you should pass by a pointer to a const argument they are of built-in types, which can be passed by copy they are to be changed inside the function and such changes should not be reflected outside, in which case you can pass by copy (an alternative would be to pass according to the previous rules and make a copy inside of the function) (here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03) There's more to this, but these few beginner's rules will get you quite far.
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 embedded app and it didn't take much more time then using these libs.
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 key from the cache and is not present can start a locked calculation for that unique key. In the meantime other threads can retrieve or calculate data for other keys but a thread that tries to access the first key get locked-wait. The main constraints are: Never calculate the value for a key at the same time. Calculating the value for 2 different keys can be done concurrently. Data-retrieval must not lock other threads from retrieve data from other keys. My other constraints but already resolved are: fixed (known at compile time) maximum cache size with MRU-based ( most recently used ) thrashing. retrieval by reference ( implicate mutexed shared counting ) I'm not sure using 1 mutex for each key is the right way to implement this but i didn't find any other substantially different way. Do you know of other patterns to implements this or do you find this a suitable solution? I don't like the idea of having about 100 mutexs. ( the cache size is around 100 keys )
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 potentially a value. The condition is signaled when the value is set. When a thread wishes to obtain a value from the cache, it first acquires the global mutex. It then looks in the map: If there is a wrapper for that key, and that wrapper contains a value, then the thread has its value and may release the global mutex. If there is a wrapper for that key but no value yet, then this means that some other thread is currently busy computing the value. The thread then blocks on the condition, to be awaken by the other thread when it has finished. If there is no wrapper, then the thread registers a new wrapper in the map, and then proceeds to computing the value. When the value is computed, it sets the value and signals the condition. In pseudo code this looks like this: mutex_t global_mutex hashmap_t map lock(global_mutex) w = map.get(key) if (w == NULL) { w = new Wrapper map.put(key, w) unlock(global_mutex) v = compute_value() lock(global_mutex) w.set(v) signal(w.cond) unlock(global_mutex) return v } else { v = w.get() while (v == NULL) { unlock-and-wait(global_mutex, w.cond) v = w.get() } unlock(global_mutex) return v } In pthreads terms, lock is pthread_mutex_lock(), unlock is pthread_mutex_unlock(), unlock-and-wait is pthread_cond_wait() and signal is pthread_cond_signal(). unlock-and-wait atomically releases the mutex and marks the thread as waiting on the condition; when the thread is awaken, the mutex is automatically reacquired. This means that each wrapper will have to contain a condition. This embodies your various requirements: No threads holds a mutex for a long period of time (either blocking or computing a value). When a value is to be computed, only one thread does it, the other threads which wish to access the value just wait for it to be available. Note that when a thread wishes to get a value and finds out that some other thread is already busy computing it, the threads ends up locking the global mutex twice: once in the beginning, and once when the value is available. A more complex solution, with one mutex per wrapper, may avoid the second locking, but unless contention is very high, I doubt that it is worth the effort. About having many mutexes: mutexes are cheap. A mutex is basically an int, it costs nothing more than the four-or-so bytes of RAM used to store it. Beware of Windows terminology: in Win32, what I call here a mutex is deemed an "interlocked region"; what Win32 creates when CreateMutex() is called is something quite different, which is accessible from several distinct processes, and is much more expensive since it involves roundtrips to the kernel. Note that in Java, every single object instance contains a mutex, and Java developers do not seem to be overly grumpy on that subject.
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. The question then is how is one expected to get a UTF-16 string into a protocol buffer ? Presumably I need to keep the data as a wstring in my application code and then perform a UTF-8 conversion before I stuff it into (or extract from) the message. What is the simplest - Windows/Linux portable way to do this (A single function call from a well-supported library would make my day) ? Data will originate from various web-servers (Linux and windows) and will eventually ends up in SQL Server (and possibly other end points). -- edit 1-- Mark Wilkins suggestion seems to fit the bill, perhaps someone who has experience with the library can post a code snippet -- from wstring to UTF-8 -- so that I can gauge how easy it will be. -- edit 2 -- sth's suggestion even more so. I will investigate boost serialization further.
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 utf-16 MultiByteToWideChar( CP_UTF8, 0, myUtf8String, -1, myUtf16Buf, lengthOfUtf16Buf ); With Linux, libidn might do what you need. It can convert between UTF-8 and UCS, which I think is equivalent to UTF-32 at some level. For example: // utf-8 to UCS ucsStr = stringprep_utf8_to_ucs4( "asdf", 4, &items ); However, in Linux I think you might be best simply working with UTF-8. Unless you have an existing library for UTF-16, I am not sure there is a compelling reason to use it in Linux.
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 in my main QGLWidget I can sort the entities and render them accordingly. I noticed though that certain openGL functions (like bindTexture) need to be called from the QGLWidget (or the widget's QGLContext). At the moment I'm passing a pointer to the QGLWidget that controls my main viewport to each entity and storing it so that I can gain access to those functions. Is this a good idea? Any advice would be gratefully received, or even directions to good websites/books that might be of help. I've got the Blanchette/ Summerfield book but the OpenGL section is quite short and most of the examples on the Qt website are pretty simplistic. Thanks, Dan
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 thread, consider storing the QGLWidget pointer as a static class member to save effort: class MyGLWidget : public QGLWidget { // ... public: static inline MyGLWidget *GetActiveWidget() { return ms_activeWidget; } protected: static __declspec(thread) MyGLWidget *ms_activeWidget = 0; // uses MSVC extension inline void SetActiveWidget() { ms_activeWidget = this; } }; void MyGLWidget::paintGL() { SetActiveWidget(); // ... } Then in your entity classes you can simply call MyGLWidget::GetActiveWidget() on the few occasions when you need to call QGLWidget member functions, and not need to copy a (probably invariant) pointer all over the place.
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 problem is related to the typedef in Bar. How can I define a constructor that will accept std::vectors of objects with the type in Bar? #include <vector> #include <iostream> #include <utility> template <typename T> struct Bar { typedef std::pair<T, T> type; // or anything else that uses T }; struct Foo { Foo() {} // CASE 1: doesn't compile template <typename T> explicit Foo( const std::vector<typename Bar<T>::type>& data ) { std::cout << "Hello\n"; } //// CASE 2: compiles, but it's not what I want //template <typename T> explicit Foo( const std::vector<Bar<T> >& data ) //{ // std::cout << "Hello\n"; //} }; int main() { std::vector<Bar<int>::type> v; // for CASE 1 //std::vector<Bar<int> > v; // for CASE 2 Foo f( v ); return 0; }
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 corresponding template-argument cannot be deduced from a function call and the template-argument must be explicitly specified. The definition of nondeduced contexts, as stated in §14.8.2.4: The nondeduced contexts are: the nested-name-specifier of a type that was specified using a qualified-id. A type that is a template-id in wich one or more of the template-arguments is an expression that references a template-parameter. In Bar<T>::type, Bar<T> is a nested-name-specifier and hence a non-deduced context, so you must explicitly specify the template argument when calling the constructor...which is not possible (i.e. you cannot write Foo f<int>(v)). I suppose the compiler cannot deduce the template argument because that would be at least cumbersome, and more probably impossible: imagine Bar is specialized: template<typename T> struct Bar { typedef std::pair<T,T> type; }; template<> struct Bar<char> { typedef std::pair<int,int> type; }; Now I have an ambiguity when calling Foo's constructor with std::vector<std::pair<int,int> >: should the template argument be int or char? And even if there was no such ambiguity, you can easily see that the compiler would have to instantiate Bar with potentially any type before finding the instantiation with the correct typedef (well, I'm not so sure above statements are truly relevant since I often find out compilers to be much more smarter than I thought :-)!)
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 frees it. Is it acceptable in C++? Is it undefined behaviour?
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* because there are no objects of type void". Arguably the object in your example doesn't have a dynamic type, since the definition of "dynamic type" at 1.3.3 mentions "most derived object", and the definition of "most derived object" at 1.8/4 is talking about objects of class type. So I kept looking: 5.2.10/3: "[reinterpret_cast] might, or might not, produce a representation different from the original value" 5.3.5/2: "The value of the operand of delete shall be the pointer value which resulted from a previous array new-expression". I'm not sure whether a reinterpret_cast results in the same pointer value as was input, or not. Possibly it's cleared up by some other bit of the standard which I haven't found yet. I would not call this code "OK" without finding something to definitively state that if you reinterpret_cast a pointer, the result is the same "pointer value" as before, so that by passing it to delete[] you are passing "the pointer value" from new[]. 5.2.10/7: "Except that casting [between certain pointer types] and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified". This looks like bad news to me - it conspicuously doesn't say that the cast yields the same value, only that the pair of casts over and back, yields the same value. This suggests to me that the single cast is allowed to yield a different value, but it is only suggestive, not explicit. This is the usual problem with the rule that "if the standard doesn't state the behavior, then the behavior is undefined". Just because it doesn't state it in any of the paragraphs I can find using the index, doesn't mean it doesn't state it somewhere else... We know that in practice we can cast things to unsigned char* in order to inspect their bytes, or void* to copy PODs using memcpy, so there must be some casts guaranteed to create aliases. You might think that if your implementation does create aliases with certain casts, then you're passing in the "same value" you got from new[]. But I'm still not sure that's good enough for delete[]. I think I'm missing something important.
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 while( __sync_val_compare_and_swap( &lock, false, true ) == true ) { // Spin while we don't acquire } // make sure we have the lock assert( lock == true ); // release the lock assert( __sync_val_compare_and_swap( &lock, true, false ) == true ); } } Ok, if I run the above code in 10 concurrent threads, all is well. However, if I change the code to read // acquire a lock while( __sync_val_compare_and_swap( &lock, lock, true ) == true ) Notice I've changed "false" to "lock". All hell breaks loose and the assertion // make sure we have the lock assert( lock == true ); Fires. Can anyone explain why this makes a difference ? Thx Mark.
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 actual atomic compare-and-swap (but after the function arguments are determined), the other thread releases the lock - lock becomes false. The compare_and_swap then will return false, but will not have performed the swap operation, because the value it compared to was not the value in the lock. This thread didn't perform the swap, so the value of lock remains false, triggering your assertion. Incidentally, I strongly suggest making lock a volatile bool. You don't want the compiler optimizing the references to such variables.
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 // so must sniff BOOL f64 = FALSE; return IsWow64Process(GetCurrentProcess(), &f64) && f64; #else return FALSE; // Win64 does not support Win16 #endif }
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 source files that use that header. These are the two main features that have meant make and its offspring are used for all serious software development with compiled languages.
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 to just push some point at the end of its internal data and the simply render it? Or if there's no such function/object, what is the way to go here? On a related topic: I don't like vtk too much. Is there a visualization toolkit, maybe with limited functionality, that is easier to use? Thanks in advance
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 connectivity information for these points). Once your vtkDataSet is constructued, you can take the normal route to render it (mapper->actor->renderer...) For example: vtkPoints *pts = vtkPoints::New(); pts->InsertNextPoint(1,1,1); ... pts->InsertNextPoint(5,5,5); vtkPolyData *polydata = vtkPolyData::New(); polydata->Allocate(); vtkIdType connectivity[2]; connectivity[0] = 0; connectivity[1] = 3; polydata->InsertNextCell(VTK_LINE,2,connectivity); //Connects the first and fourth point we inserted into a line vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput(polydata); // And so on, need actor and renderer now There are plenty of examples on the documentation site for all the classes Here is vtkPoints : http://www.vtk.org/doc/release/5.4/html/a01250.html If you click on the vtkPoints (Tests) link, you can see the tests associated with the class. It provides a bunch of different sample code. Also, the vtk mailing list is probably going to be much more useful than stack overflow.
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 parameter? Stuff along the lines: Man, in peer reviews I always see other programmers do this when they could have easily done it this way. Part Two of my question deals with some specific cases I've encountered where I would like to avoid an out parameter but cannot think of a clean way to do so. Example 1: I have a class with an expensive copy that I would like to avoid. Work can be done on the object and this builds up the object to be expensive to copy. The work to build up the data is not exactly trivial either. Currently, I will pass this object into a function that will modify the state of the object. This to me is preferable to new'ing the object internal to the worker function and returning it back, as it allows me to keep things on the stack. class ExpensiveCopy //Defines some interface I can't change. { public: ExpensiveCopy(const ExpensiveCopy toCopy){ /*Ouch! This hurts.*/ }; ExpensiveCopy& operator=(const ExpensiveCopy& toCopy){/*Ouch! This hurts.*/}; void addToData(SomeData); SomeData getData(); } class B { public: static void doWork(ExpensiveCopy& ec_out, int someParam); //or // Your Function Here. } Using my function, I get calling code like this: const int SOME_PARAM = 5; ExpensiveCopy toModify; B::doWork(toModify, SOME_PARAM); I'd like to have something like this: ExpensiveCopy theResult = B::doWork(SOME_PARAM); But I don't know if this is possible. Second Example: I have an array of objects. The objects in the array are a complex type, and I need to do work on each element, work that I'd like to keep separated from the main loop that accesses each element. The code currently looks like this: std::vector<ComplexType> theCollection; for(int index = 0; index < theCollection.size(); ++index) { doWork(theCollection[index]); } void doWork(ComplexType& ct_out) { //Do work on the individual element. } Any suggestions on how to deal with some of these situations? I work primarily in C++, but I'm interested to see if other languages facilitate an easier setup. I have encountered RVO as a possible solution, but I need to read up more on it and it sounds like a compiler specific feature.
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 that's it's a member of ExpensiveCopy (which you say you can't do, so that's out) return a (smart) pointer from doWork instead of copying it. (which you don't want to do as you want to keep things on the stack) Rely on RVO (which others have pointed out is supported by pretty much all modern compilers)
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 of the 3D graphics frameworks in Snow Leopard. Are any of the graphic frameworks 64 bit only?
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] documentView] bounds]]; } This code seems to fix the problem, indeed displaying objects with -webkit-transform: -(NSBitmapImageRep *)getBitmap { NSBitmapImageRep *image = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]]; [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:image]; return image; }
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 executable when it is already built. I found the answer in ermine & statifier
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 machine has an API compatible (major version 1) but different minor version 2.3, which would probably work with your program if only it would link the major version of the library has changed, which means it is incompatible libc.so.2 vs libc.so.1. The fixes are: don't link libraries which you don't need that may not be on different distros, OR, install the additional libraries on the other machines, either manually or make them dependencies of your installer package (e.g. use RPM) don't specify the versions so tightly on the command line - link libz.so.1 instead of libz.so.1.2.3. compile multiple versions against different libc versions.
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(); // Okay. Foo is public in this context. } Is this legal C++? "This" being changing the virtual function's access mode in the derived class.
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, there's no need to ever make them anything but private. As to why you would actually make something public in base but private in derived without private or protected inheritance is beyond me.
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 be called from, potentially forcing yourself to think a little bit more about the scope of the function. I'm still on the side of doing the prototype, but I can see arguments aren't completely baseless for the other side of the fence. I suppose this argument could also be continued on to #define and file scope variables.
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 syntax of a declaration/definition (i.e., declaring the number and types of parameters in the parameter list). To be clear, the following declaration and definition use prototype syntax: /** * prototype declaration; the number and types of parameters are * part of the declaration, so the compiler can do type checking * on the function call */ double f(int x, int y, double z); /** * prototype definition */ double f(int x, int y, double z) { ... } whereas the following declaration and definition do not use prototype syntax: /** * non-prototype declaration; the number and types of parameters * are not specified, so the compiler can't do any type checking * on the function call. */ double f(); ... /** * non-prototype definition; this is still legal AFAIK, but * *very* outdated, and should no longer be used */ double f(x, y, z) int x; int y; double z; { ... } Whether you define functions before use, or just declare before use and define later, always use prototype syntax.
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 on the MyComparator instance held by the priority queue. Is there any way to either: get access to the MyComparator instance held by the priority queue, or: somehow pass the original MyComparator instance in by reference
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 a suitable copy constructor and copy assignment operator. If you want your comparison object to containt mutable state then the problem is more complex as any copies of your comparison object need to share the mutable state. If you can maintain the state as a separate object then you can have your comparison objects keep a pointer to this external state; if not you will probably find that you need shared ownership of the common state so you will probably require something like tr1::shared_ptr to manage this.
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().c_str()); You can get an std::string object with the result using 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) As A End Function So what I'm trying to do above it just import the lovely overloaded operator + from the DLL. Note that the operator is already overloaded from inside the DLL, so should I import it as a Function or as an Operator like this? <DllImport("StructDLL.dll")> Public Shared Operator +(ByVal a1 As A, ByVal a2 As A) As A End Operator The overloaded plus operator is supposed to add structs. So the DLL is programmed to work on structs (C++) and I want to import it in VB.NET to work on Structures.
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, string outFilename) { ifstream infile(inFilename.c_str(), ios::binary); ofstream outfile(outFilename.c_str(), ios::binary); if( infile.is_open() && outfile.is_open() && infile.good() && outfile.good() ) { outfile << infile.rdbuf(); outfile.close(); infile.close(); } else return 1; return 0; } Any insight?
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 dwType, dwSize; dwType = REG_DWORD; dwSize = sizeof(DWORD); DWORD rofl = 1; RegSetValueEx(hkey, TEXT("value"), 0, dwType, (PBYTE)&rofl, dwSize); // does not create anything RegCloseKey(hkey); } But it doesnt do anything. RegCreateKeyEx() is the only function that actually does something: creates the "folders" in the registry only. So once again how im failing? How i can create "files" in the registry?
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, &dwDisposition) == ERROR_SUCCESS) { // etc.. }
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 wide char and needs to be converted using WideCharToMultiByte. If you are using Visual Studio, which I assume you are, you can change this setting in the project properties under Character Set.
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 on; however, I'm wondering if this is well defined behaviour that should be expected? For clarity, the code that causes this is something along these lines: int x; //uninitialized getAValueForX( &x ); // function makes use of x, // but x is unitialized where void getAValueForX( int *x ) { *x = 4; } or something along those lines, obviously more complex.
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 mechanics). There are very good references (or introductory books) for each one of those topics separately.
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; } return 0; } void Test2(Base arr[]) { for (int i=0;i<5;++i) { arr[i].Foo(i); } } void main { Base* b = new Derived[5]; Test(b); } So, when i'm calling Test, after the second loop there a memory viloation exception. I have 2 questions: What's the difference between the function argument in Test and Test2 ? (Test2 doesn't compile after i turned Base into pure abstract class). and the more important question How can i prevent that exception, and how can i pass an array of derived class to a function that suppose to get a base class array. (i can't tell in compile time which derived class i'm gonna pass the function) p.s - please don't tell me to read Meyers book, that's the exact reason why i'm asking this question. :) Thanks
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, the pointer arithmetic done on that pointer will be based on the element size of the array type. To deal with arrays of polymorphic types, you'll need to add another level of indirection and deal with arrays (or some other container) of pointers to the objects. Test2 doesn't compile after i turned Base into pure abstract class You can't have arrays of abstract types because you can't have instances of abstract types (only pointers or references to them).
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: int d; protected: int e; private: int f; }; I understand that if a class is inherited privately from the base class, everything is private in the derived class. But why in the code above, the function f() can access a, b, d, e, f but not c?
'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 sloItemClicked get called more than once, it seem that it get called X time where X is the number of row in my table. But it is calling for the same row all the time. (QTableWidgetItem that I receive is the same). This is a problem, because when the row is clicked, I delete it. So the next time it gets called, the QTableWidgetItem is no longer valid and it crash. If I have only one row, everything works as expected.. Any idea? Thanks
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 in "higher" languages like Ruby/Python/Java (since GC prevents predictable destruction of objects). I'm curious -- what other techniques do you know of that are very C++ specific, due to language design choices. Thanks! Edit: If your answer is "this works in C++ & this other langauge", that's okay too. The things I want to learn about are similar to: By choosing to not have certain features (like GC), we gain other features (like RAII + predicable destructing of objects). In what areas of C++, by choosing to NOT have features that other "higher level" langauges have, C++ manages to get patterns that those higher level langauges can't express.
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 you make a class that has a hash defined for all the types that you want? You can declare a class such as: template < typename T> struct hashing_tratis { typedef std::tr1::hash<T> hashing_type; }; that is, you expect a class that has the correct hasing_type defined to be used. However, hash is not defined, say, for myType, so you can write: template <> struct hashing_traits<myType> { typedef class_that_knows_how_to_hash_myType hashing_type; }; This way, suppose that you need a way to hash any type that you use in your program (including myType). You can write an "universal" hasher by creating a hasing trait: template <typename T> struct something { typename hashing_traits<T>::hashing_type hasher; .... // here hasher is defined for all your relevant types, and knows how to hash them
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 limit. Unfortunately, I haven't found a suitable way to achieve this in practice. Without this feature, the application is pretty much dead in the water. So I've hit a huge road block, and I'm open to any suggestions. With my application, I need to achieve two requirements: Drop all internet activity. and then Turn on only internet activity to a specified port and IP address. (my service, which will be polled) Simple goal, right? Not so much lately. While I am looking to achieve this in C#, I understand that may be a long-shot and I am open to C++ solutions that could be called as a resource through my application. Also note, I cannot install any third-party software on the user's system, as this solution needs to be all-encompassing. Thanks in advance!
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 designed for use by programmers using C/C++ development software. Programmers should be familiar with networking concepts and design of systems using user-mode and kernel-mode components.
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.pop_back(); // argh This is more frequent (the copy-pop) on adapter's like stack. Could something like this exist: SomeExpensiveType x = vec.move_back(); // move and pop To avoid a copy? And does this already exist? I couldn't find anything like that in n3000. I have a feeling I'm missing something painfully obvious (like the needlessness of it), so I am prepared for "ru dum". :3
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 have 32 bits, or whatever. "Ints don't have any member functions." Well, they have a whole bunch of operators like + and -.
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 initializes a to 1 I considered extending this notion to allow derivation from built-in classes and explicit declaration of built-in operators for built-in types. However, I restrained myself. Allowing derivation from an int doesn't actually give a C++ programmer anything significantly new compared to having an int member. This is primarily because int doesn't have any virtual functions for the derived class to override. More seriously though, the C conversion rules are so chaotic that pretending that int, short, etc., are well-behaved ordinary classes is not going to work. They are either C compatible, or they obey the relatively well-behaved C++ rules for classes, but not both. As far as the comment the performance justifies not making int a class, it's (at least mostly) false. In Smalltalk all types are classes -- but nearly all implementations of Smalltalk have optimizations so the implementation can be essentially identical to how you'd make a non-class type work. For example, the smallInteger class is represents a 15-bit integer, and the '+' message is hard-coded into the virtual machine, so even though you can derive from smallInteger, it still gives performance similar to a built-in type (though Smalltalk is enough different from C++ that direct performance comparisons are difficult and unlikely to mean much). The one bit that's "wasted" in the Smalltalk implementation of smallInteger (the reason it only represents 15 bits instead of 16) probably wouldn't be needed in C or C++. Smalltalk is a bit like Java -- when you "define an object" you're really just defining a pointer to an object, and you have to dynamically allocate an object for it to point at. What you manipulate, pass to a function as a parameter, etc., is always just the pointer, not the object itself. That's not how smallInteger is implemented though -- in its case, they put the integer value directly into what would normally be the pointer. To distinguish between a smallInteger and a pointer, they force all objects to be allocated at even byte boundaries, so the LSB is always clear. A smallInteger always has the LSB set. Most of this is necessary, however, because Smalltalk is dynamically typed -- it has to be able to deduce the type by looking at the value itself, and smallInteger is basically using that LSB as a type-tag. Given that C++ is statically typed, there's never a need to deduce the type from the value, so you probably wouldn't need to "waste" that bit on a type-tag. 1. In The Design and Evolution of C++, §15.11.3.
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 to initialize the variable in both cases (T == class, T == int, char, bool, ...)?
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() blocks until all the operations are complete. Having read the definitions, I figured that if I were to use glFlush() that I would probably run into the problem of submitting more operations to OpenGL than it could execute. So, just to try, I swapped out my glFinish() for a glFlush() and lo and behold, my program ran (as far as I could tell), the exact same; frame rates, resource usage, everything was the same. So I'm wondering if there's much difference between the two calls, or if my code makes them run no different. Or where one should be used vs. the other. I also figured that OpenGL would have some call like glIsDone() to check whether or not all the buffered commands for a glFlush() are complete or not (so one doesn't send operations to OpenGL faster than they can be executed), but I could find no such function. My code is the typical game loop: while (running) { process_stuff(); render_stuff(); }
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 scene that appears object after object on the screen, when you call glFlush after each object. However, when using double buffering, glFlush has practically no effect at all, since the changes won't be visible until you swap the buffers. glFinish does not return until all effects from previously issued commands [...] are fully realized. This means that the execution of your program waits here until every last pixel is drawn and OpenGL has nothing more to do. If you render directly to the front buffer, glFinish is the call to make before using the operating system calls to take screenshots. It is far less useful for double buffering, because you don't see the changes you forced to complete. So if you use double buffering, you probably won't need neither glFlush nor glFinish. SwapBuffers implicitly directs the OpenGL calls to the correct buffer, there's no need to call glFlush first. And don't mind stressing the OpenGL driver: glFlush will not choke on too many commands. It is not guaranteed that this call returns immediately (whatever that means), so it can take any time it needs to process your commands.
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 { /* ... */ }; template<class X> class B { /* ... */ }; and I want to instantiate each one as the following: // Pseudocode -- not valid C++. A<B> a; B<A> b; that is, I want to 'bind' A to B, and B to A. I can solve the problem, in a gross way, through a forward declaration with inheritance trick: class sA; class sB; class sA : public A<sB> { /* ... */ }; class sB : public B<sA> { /* ... */ }; but this brings in a set of problems, since sA and sB are not indeed A and B. For example, I cannot invoke A's constructors without properly duplicating them into sA, or somehow sparkling casts around the code. My question is: what is the best practical way to deal with this issue? Any specially clever solution to this problem? I am using both MSVC2008 and G++, but solutions with compiler-specific extensions are welcome. Thanks, Alek
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. template< class W > // define an abstract class to pass data struct widget_traits {}; template<> struct widget_traits< SpringySpring > { // specialize to put data in it struct properties { … }; enum { boing = 3 }; }; template< class V > struct veeblfetzer_traits {}; template<> struct veeblfetzer_traits< VonNeumann > { typedef int potrzebie; }; template< struct WT, struct VT > // pass info by using as argument struct MyWidget { … }; template< struct VT, struct WT > // both ways struct MyVeeblfetzer { … };
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 : public Base { // ... snipped bool operator==( const Derived& other ) const { return ( static_cast<const Base&>( *this ) == static_cast<const Base&>( other ) ? age_ == other.age_ : false ); }; Now when I instantiate and compare like this ... Derived p1("Sarah", 42); Derived p2("Sarah", 42); bool z = ( p1 == p2 ); ... all is fine. Here the operator== from Derived gets called, but when I loop over a list, comparing items in a list of pointers to Base objects ... list<Base*> coll; coll.push_back( new Base("fred") ); coll.push_back( new Derived("sarah", 42) ); // ... snipped // Get two items from the list. Base& obj1 = **itr; Base& obj2 = **itr2; cout << obj1.asString() << " " << ( ( obj1 == obj2 ) ? "==" : "!=" ) << " " << obj2.asString() << endl; Here asString() (which is virtual and not shown here for brevity) works fine, but obj1 == obj2 always calls the Base operator== even if the two objects are Derived. I know I'm going to kick myself when I find out what's wrong, but if someone could let me down gently it would be much appreciated.
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 of logic into your operator==. First make it virtual, so the type of the left-hand operand is determined at runtime. Then manually check the type of the right-hand operand. virtual bool operator==( const Base& other ) const { if ( ! Base::operator==( other ) ) return false; Derived *other_derived = dynamic_cast< Derived * >( &other ); if ( ! other_derived ) return false; return age_ == other_derived->age_; } but considering that objects of different types probably won't be equal, probably what you want is virtual bool operator==( const Base& other ) const { Derived *other_derived = dynamic_cast< Derived * >( &other ); return other_derived && Base::operator==( other ) && age_ == other_derived->age_; }
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 process isn't there. Handle connection setup in a separate connect() method, returning an error code if the process isn't there. In option 1), the calling code will of course have to wrap its instantiation of that class and everything else that deals with it in a try() block. In option 2, it can simply check the return value from connect(), and return (destroying the object) if it failed, but it's less RAII-compliant, Relatedly, if I go with option 1), is it better to throw one of the std::exception classes, derive my own exception class therefrom, roll my own underived exception class, or just throw a string? I'd like to include some indication of the failure, which seems to rule out the first of these. Edited to clarify: The remote process is on the same machine, so it's pretty unlikely that the ::connect() call will block.
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 from std::exception. This allows the catcher to perform an action for that specific type of exception with a catch (const myexception &e) {...} statement, and also do one thing for all exceptions with a catch (const std::exception &e) {...}. See related question: How much work should be done in a constructor?
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 think i found my mistake with using the __LINE__ macro. I feel a kinda stupid now.. I think i have to go to bed (after some time you are not creating/adding anything new but destroying what you have done so far). Problem solved, thanks all for your help!
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__); } /* Source2.c */ ...list of headers & functions .... if (!(p = (char *)malloc((10 * sizeof(char)) + 1)))){ fprintf(stderr, "Error in %s @ line: %d: Could not malloc\n", __FILE__, __LINE__); } /* Source3.c */ ...list of headers & functions .... if (!(ptr = (char *)malloc((50 * sizeof(char)) + 1)))){ fprintf(stderr, "Error in %s @ line: %d: Could not malloc\n", __FILE__, __LINE__); } Suppose those three files are compiled and linked into an executable called foo.exe and runtime errors appear, nitpicky aside, you would get: Error in source2.c @ line 25: Could not malloc Error in source1.c @ line 50: Could not open foo.blah Error in source3.c @ line 33: Could not malloc The total size of the project sources in terms of line count, does not mean that those lines are out of sync, regardless of what was pre-processed. I hope I have explained it somewhat easier for you to understand in aiding your reasoning behind the usage of the __LINE__ macro. Hope this helps, Best regards, Tom.
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 declaration solves that problem class bar; Now, here is the problem - when writing the header files, each header depends on the other: foo.h needs the definitions in bar.h and vice-versa. What is the proper way of dealing with this?
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 can't put definitions that require member information into your header - move it to the .cpp file. The .cpp files can include both foo.h and bar.h: // Foo.cpp #include "foo.h" #Include "bar.h" void foo::some_method() { this->m_pbar->do_something(); // Legal, now, since both headers have been included }
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) binds to a lvalue (another non-const object), a copy of the object is made automatically while creating the parameter (s). However, when s binds to a rvalue (temporary object, literal), the copy is typically elided, which saves a call to a copy constructor and a destructor. In the earlier version of the assignment operator where the parameter is accepted as const reference, copy elision does not happen when the reference binds to a rvalue. This results into an additional object being created and destroyed.
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 arrange that foo() will directly construct its return value into c. Here's another example. Let's say you have a function: void doit(CLASS c); If you call it with an actual argument, the compiler has to invoke the copy constructor so that the original parameter cannot be modified: CLASS c1; doit(c1); But now consider a different example, let's say you call your function like this: doit(c1 + c1); operator+ is going to have to create a temporary object (an rvalue). Instead of invoking the copy constructor before calling doit(), the compiler can pass the temporary that was created by operator+ and pass that to doit() instead.
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 void is not a value and that it cannot be treated like one. With my logic it would make sense and it should be possible to do that. I mean, why not? Any argument why that should not be possible?
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 forwarding function work without having to worry about whether the function being forwarded has void return. So, if a similar system applied so that a void return constituted a nullary call in a function composition scenario, that could make function composition more generic too.
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 Intel C++ Compiler 11.1 accept both of these without warnings; Comeau 4.3.10.1b2 and g++ 3.4.5 (which is, admittedly, not particularly recent) do not. According to the C++ standard (C++03 5.2.3/2, expr.type.conv): The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized 7.1.5.2 says, "the simple type specifiers are," and follows with a list that includes unsigned and int. Therefore, given that in 5.2.3/2, "simple-type-specifier" is singular, and unsigned and int are two type specifiers, are the examples above that use unsigned int invalid? (and, if so, the followup is, is it incorrect for Microsoft and Intel to support said expressions?) This question is more out of curiosity than anything else; for all of the types specified by a combination of multiple simple type specifiers, value initialization is equivalent to zero initialization. (This question was prompted by comments in response to this answer to a question about initialization).
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 that the header of Table 7 (which is Table 9 in the most recent draft N3000) is somewhat misleading, but the preceeding text in [dcl.type.simple]/2 looks very clear to me, when it says: Table 7 summarizes the valid combinations of simple-type-specifiers and the types they specify." (I apologize it took me so long to post this back here from the newsgroup; it completely slipped my mind)
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(cin, input); sstream.str(input); sstream >> first; cout << first << endl; //display user input in integers cout << "Second integer: "; getline(cin, input); sstream.str(input); sstream >> second; cout << second << endl; //display user input in integers getline(cin, input); //pause program return 0; } However, the second time around it seems to give the variable 'second' an arbitrary value. This is the output: First integer: 1 1 Second integer: 2 2293592 If I declare two stringstream objects and use them respectively for both variables it seems to work fine. Does this mean that I cannot re-use a stringstream object in the way I'm trying to do? In my real program I intend to handle much more than two input values from the user, so I just want to make sure if there's another way instead of making multiple stringstream objects. I doubt it's of great relevance but I'm on Windows XP and I'm using MinGW as my compiler. I greatly appreciate any help.
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, &isSuccessful); return (hr == S_FALSE) ? E_FAIL : hr; } Note: m_pXmlDoc is of the type CComPtr<IXMLDOMDocument>. It appears that the call to IXMLDOMDocument::load() (marked with the *) is failing - IOW, it is returning S_FALSE. I am not able to step into load() to determine why it is failing, as it is a COM call. The MSDN page for this method doesn't seem to be giving a lot of insight. I have a few hunches: The XML is not well-formed The XML file is too large (approximately 120MB) It is a memory-related issue (the process size gets to > 2GB at the time of failure) NB: A registry key has been set to allow the process size to be this large, as the largest valid process size for WinXP, AFAIK, is 2GB). Any ideas as to why this call could be failing?
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); pError->get_line(&nLine); pError->get_linepos(&nColumn); } sReason will be filled with the error message. sSource will contain the errorneous source line in the XML. nLine and nColumn should get set to the line number and column of the error, although in practice these two aren't always set reliably (iirc, this is especially true of validation errors, rather than parser/well-formedness ones).
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 printf() and fprintf(std***) and am thinking I have the following options: Fork in my C++ app, create a pipe from (f)printf() calls to the new processes stdin, and start a Java program that reads from stdin and logs using Commons Logging Create a JVM in the C++ app using JNI's JNI_CreateJVM() and invoke a Java logging method when the (f)printf() calls are made Use something like Log4cxx to read the same configuration as the Java app and log natively in C++ I'd like to avoid option 3 as much as possible because I don't want to add another third-party dependency to my applications. I understand there is a performance cost to crossing from C++ to Java, but I'm not sure if it will matter that much.
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, you would need to log everything at trace level into stdout (because the C++ code does not know about the configured log levels), which also sounds excessive . Go with Log4cxx, or make some C++ code that can read the configuration file yourself. (*) Okay, option 4 (have a wrapper script that redirects stderr/stdout from your unmodified C++ program to a Java program that translates the output into log entries) would not be very complex.
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 pointer? I found a function which uses it, but the class I use only allows for you to rewrite functions, not access individual lines. Here is what the assembly looks like from IDA... I need to get the value of "gpszVersionString_ptr" http://www.ampaste.net/m57f13aba Edit Sorry, it lost formatting so i had to ampaste it.
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 function looks like it is used to draw an icon, and the style options should include whether it is selected. The simplest fix would be to override that function, set the selected flag in the options to false, then pass it up to the parent's function.
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 do you? This will help me understand some practical applications for pointers, so thanks!
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 which it was created. When I need to allocate an object whose size is unknown at compile time. When I need to transfer ownership of an object from one thing to another without actually copying it (like in a linked list/heap/whatever of really big, expensive structs) When I need to refer to the same object from two different places. When I need to slice an array without copying it. When I need to write directly to a specific region of memory (because it has memory-mapped IO).
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) { CWPSTRUCT* info = (CWPSTRUCT*) lParam; if(info->message == WM_SETFOCUS ) { if(info->hwnd == hControl) { MessageBox(NULL,L"Focus on control",L"Focus",MB_OK); } } } return CallNextHookEx(hhookCallWndProc , nCode, wParam, lParam); } Now when I focus on the control, this hook procedure is getting called . MessageBox is shown. But as soon as I click on Ok , another message pops up. Messages keep on popping up infinitely. I want to get messagebox only once whenever I focus on control, but here I am getting messages infinitely. Anything I am doing wrong.
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*/); boost::shared_ptr<foo> create_foo() { boost::shared_ptr<foo> p_foo(new foo); init_fields(p_foo); init_other_fields(p_foo); } Question 2 Should I use boost::make_shared to construct a shared_ptr? If yes, what advantages it offers? And how can we use make_shared when T doesn't have a parameter-less constructor? Question 3 How to use const foo*? I have found two approaches for doing this. void take_const_foo(const foo* pfoo) { } int main() { boost::shared_ptr<foo> pfoo(new foo); take_const_foo(pfoo.get()); return 0; } OR typedef boost::shared_ptr<foo> p_foo; typedef const boost::shared_ptr<const foo> const_p_foo; void take_const_foo(const_p_foo pfoo) { } int main() { boost::shared_ptr<foo> pfoo(new foo); take_const_foo(pfoo); return 0; } Question 4 How can I return and check for NULL on a shared_ptr object? Is it something like, boost::shared_ptr<foo> get_foo() { boost::shared_ptr<foo> null_foo; return null_foo; } int main() { boost::shared_ptr<foo> f = get_foo(); if(f == NULL) { /* .. */ } return 0; } Any help would be great.
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 you will know whether to pass by reference or by value. From a performance point of view, it's usually a better idea to use a boost pointer container instead of a container of shared_ptr.
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 a property of an object, but rather a property of an expression (i.e. a property of its result). This is actually how it is defined in the language specification: for different kinds of expressions it says when the result is an lvalue and when it is an rvalue. Among other things, this actually means that a temporary object can be accessed as an rvalue as well as an lvalue, depending on the specific form of expression that is used to perform the access. For example, the result of literal 2 + 3 expression is obviously an rvalue, a temporary of type int. We cannot apply the unary & to it since unary & requires an lvalue as its operand &(2 + 3); // ERROR, lvalue required However, as we all know, a constant reference can be attached to a temporary object, as in const int &ri = 2 + 3; In this case the reference is attached to the temporary, extending the lifetime of the latter. Obviously, once it is done, we have access to that very same temporary as an lvalue ri, since references are always lvalues. For example, we can easily and legally apply the unary & to the reference and obtain a pointer to the temporary const int *pi = &ri; with that pointer remaining perfectly valid as long as the temporary persists. Another obvious example of lvalue access to a temporary object is when we access a temporary object of class type through its this pointer. The result of *this is an lvalue (as is always the case with the result of unary * applied to a data pointer), yet it doesn't change the fact that the actual object might easily be a temporary. For a given class type T, expression T() is an rvalue, as explicitly stated in the language standard, yet the temporary object accessed through *T().get_this() expression (with the obvious implementation of T::get_this()) is an lvalue. Unlike the previous example, this method allows you to immediately obtain a non-const-qualified lvalue, which refers to a temporary object. So, once again, the very same temporary object might easily be "seen" as an rvalue or as an lvalue depending on what kind of expression (what kind of access path) you use to "look" at that object.
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 (usually useful only if you want to rethrow it with added context into a higher level).
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 here's the .cpp file: #include "impfactory.h" using namespace oxygen; using namespace boost; shared_ptr<ImpFactory> ImpFactory::GetInstance(){ if (mInstance.get() == 0) mInstance = shared_ptr<ImpFactory>(new ImpFactory()); return mInstance; } The code compiles, but I get a linker error: ../../lib/oxygen/liboxygen.so.3.2.4: undefined reference to `oxygen::ImpFactory::mInstance' This currently has three students stumped. Any ideas?
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 need Symbian C++? Is there any other way to develop on Symbian? What about Qt and Ovi? What way you will choose if you are going to develop on Symbian? I know this question might be somewhat subjective but I really need your help~ Thank you
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 trying to do something that JavaME cannot do (telephony...) or when the JVM footprint creates a performance problem (startup time...). JavaME is particularly useful when you plan on porting what you develop to non-Symbian phones (Although JavaME quickly becomes a nightmare when supporting multiple platforms). It is also a good entry point into the mobile industry for the many developers who were only ever trained to develop in Java. If Java ME can run on Symbian ,why we need Symbian C++? See above: Although modern JVMs execute bytecode at a rate pretty close to compiled C++, the JVM itself has a considerable footprint and J2ME simply lacks a range of APIs that are accessible in Symbian OS C++ Is there any other way to develop on Symbian? What about Qt and Ovi? Python is popular, There is a Ruby runtime, you can use the Web Runtime... You can pretty much create your own runtime if you feel like it. Qt is the next big thing because it is close to the hardware, available on other platforms and Nokia is commited to expand its API coverage. OVI isn't a development environment. It is the Nokia application store where you can upload developed applications (written in Qt, C++, Java, JavaScript...) so Nokia handset users can download them on their phones. What way you will choose if you are going to develop on Symbian? We're now back to "it depends". If you're looking for good guides, I suggest looking at the Symbian Press books, particularly the Java, Python and Quick Recipes books.
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 Child extends Parent (in case of Java Lang.) { int prop3; int prop4; public static void Main() { Child aChild = new Child(); Parent aParent = new Parent(); aParent = aChild;// is perfectly valid. aChild = aParent;// is not valid. Why?? } } Why isn't this statement valid? aChild = aParent;// is not valid. Why?? since aChild's members are superset of aParent's members. Then why can't aChild accommodate a parent.
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 involved. This is a Ancestor/Descendant inheritance relation. Inheritance is "type of" not "contains". Hence it's Fox is a type of Animal, in your case it doesn't sound right -- "Child is a type of Parent" ? The naming of classes was the source of confusion ;). class Animal {} class Fox : Animal {} class Fish : Animal {} Animal a = new Fox(); // ok! Animal b = new Fish(); // ok! Fox f = b; // obviously no!
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 this: map<prmEdge,vector<prmNode> > archi; this is the code: { bool prmPlanner::insert_edge(int from,int to,int h) { prmEdge e; int f=from; int t=to; if(to<from){ f=to; t=from; } e.setFrom(f); e.setTo(t); vector<prmNode> app; prmNode par=nodes[e.getFrom()]; prmNode arr=nodes[e.getTo()]; app.push_back(par); app.push_back(arr); archi.insert(pair<prmEdge,vector<prmNode> >(e,app) ); return true; } } In this way, I have an error in compilation in the class pair.h. What could I do?? Thank you very much.
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 comparator function for map. class EdgeComparator { public: bool operator( )( const prmEdge& emp1, const prmEdge& emp2) const { // ... ? } }; map<prmEdge,vector<prmNode>, EdgeComparator > archi; The really hard part is deciding how to compare the edges so a definitive order is defined. Assuming that you only have from and to You can try with: class EdgeComparator { public: bool operator( )( const prmEdge& emp1, const prmEdge& emp2) const { if ( emp1.from != emp2.from ) return ( emp1.from < emp2.from ); return ( emp1.to < emp2.to ); } }; It will sort on primary key from and secondary to.
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; }; This is compiled with Microsoft SDK that has the following typedefs: typedef long LONG_PTR; typedef LONG_PTR LPARAM; The calling code does the following: MyClass instance( new char[1000] ); LPARAM castResult = (LPARAM)instance; // Then we send message intending to pass the address of the buffer inside MyClass ::SendMessage( window, message, wParam, castResult ); Suddenly castResult is 1 - MyClass::operator bool() is invoked, it returns true which is converted to 1. So instead of passing the address I pass 1 into SendMessage() which leads to undefined behaviour. But why is operator bool() invoked in the first place?
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 newFriend; }; class Bar { public: Bar(){} void callFriendlyFunction() { friendlyFoo.privateFunction(); } private: friends<Foo, Bar> friendlyFoo; }; int main(int argc, char* argv[]) { Bar bar; bar.callFriendlyFunction(); return 0; } Getting a compiler error about trying to call a private function, so apparently it didn't work. Any ideas?
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 similar library which has this behaviour? I would hate to use the is_initialized method each time before dereferencing the object, and I'd also like to avoid wrapping the optional class in my own class to get this behaviour.
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 always instead, and throw inside the function if it fails?
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 a simple example) about how to obtain my own local IP address using this function ? Just to be clear when I say local, if a router is 192.168.0.1 , my local IP address could be something like 192.168.0.x ( just an example ).
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 <netinet/in.h> #include <arpa/inet.h> #include <net/if.h> #include <ifaddrs.h> #include <errno.h> int main(int argc, char *argv[]) { struct ifaddrs *myaddrs, *ifa; void *in_addr; char buf[64]; if(getifaddrs(&myaddrs) != 0) { perror("getifaddrs"); exit(1); } for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if (!(ifa->ifa_flags & IFF_UP)) continue; switch (ifa->ifa_addr->sa_family) { case AF_INET: { struct sockaddr_in *s4 = (struct sockaddr_in *)ifa->ifa_addr; in_addr = &s4->sin_addr; break; } case AF_INET6: { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)ifa->ifa_addr; in_addr = &s6->sin6_addr; break; } default: continue; } if (!inet_ntop(ifa->ifa_addr->sa_family, in_addr, buf, sizeof(buf))) { printf("%s: inet_ntop failed!\n", ifa->ifa_name); } else { printf("%s: %s\n", ifa->ifa_name, buf); } } freeifaddrs(myaddrs); return 0; }
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. Am I correct?
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 sticking with .h. Particularly, don't use .H, or you will be in a world of pain if you ever need to port to case-insensitive file system.
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 libs or just how I could better search on this topic?
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 constructor do I must define it again at the constructor of the class? Test::Test(void) { SomeClass anInstance(constructor parameters); } Thanks in advance! EDIT: Mmmm, sorry but I don't catch what you're talking about so let me show you a better example: class A { public: A(int p1,int p2); } class B { public: B(A *p1,int p2); } class C { public: C(void); private: A instanceA; B instanceB; } Then, at the implementation of the constructor of the class C I want to create instanceA and pass it to the constructor of instanceB. Hope this clarifies the question.
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 int to initialise the instance, you need: Test::Test( int someval ) : anInstance( someval ) { } Edit: To do what you are asking about in your edit, you may be better off creating the objects dynamically and using pointers. However, you can do it with values too (using a struct to minimise my typing effort): struct C { int a; int b; C() : a(1), b(a) { } }; If you do this, note that the initialisation order is the order the member variables appear in the class/struct, not the order in the initialisation list.
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 handled something do_something(); } Is this a valid way to use continue? Are continue statements ignored by switch statements? Do C and C++ differ on their behaviour here?
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 tries again with another something, until it evaluates to false), you'll need a different structure. For example: do { something = get_something(); } while (!(something == A || something == B)); do_something();
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++) result[i] = charset[rand() % charset.length()]; return result; } But the seed(time(NULL)) is not random enough.Are there any other better way to generate random strings in C++?
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 ; objC.add() ; objC.~c() ; // this line compiles objC.c() ; // compilation error }
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 the object is destroyed. If this could always done automatically, then the language would also forbid explicit destructor calls. However, in some circumstances, you might want precise control over memory management, and the ability to explicitly create and destroy objects within memory that you are managing. For this purpose, the language provides "placement new" to create an object at an arbitrary location, and explicit destructor calls to destroy objects created this way. An explicit constructor call wouldn't be useful, since you need to be able to specify the location of the new object - so you get "placement new" instead. An explicit destructor call is sufficient, so there's no need to invent some sort of matching "placement delete". So: there is no valid use for explicit constructor calls, so they are not allowed. There is a valid use for explicit destructor calls, so they are (syntactically) allowed, with the rule that you must only ever use them on objects that won't otherwise be destroyed, i.e. objects created using "placement new", and in that case call them exactly once. Using them in any other way, like so many C++ errors, will compile but give undefined behaviour.
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 also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr's construction overhead. This eliminates one of the major efficiency complaints about shared_ptr.
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 try to always use make_shared.
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 the signature void (AnyClass::*)(void)? Thanks mates. EDIT: This code has to work on Windows and also on a real-time OS (VxWorks) so not using external libraries would be great. EDIT2: Just to be sure, what I need is to have a Timer class that take an argument at the Constructor of tipe "AnyClass.AnyMethod" without arguments and returning void. I have to store this argument and latter in a point of the code just execute the method pointed by this variable. Hope is clear.
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 : public Callback { // pointer to member function void (*function)(void); public: BasicCallback(void(*_function)(void)) : function( _function ) { }; virtual void call() { (*function)(); }; }; template <class AnyClass> class ClassCallback : public Callback { // pointer to member function void (AnyClass::*function)(void); // pointer to object AnyClass* object; public: ClassCallback(AnyClass* _object, void(AnyClass::*_function)(void)) : object( _object ), function( _function ) { }; virtual void call() { (*object.*function)(); }; }; Now you can just use Callback as a callback storing mechanism so: void set_callback( Callback* callback ); set_callback( new ClassCallback<MyClass>( my_class, &MyClass::timer ) ); And Callback* callback = new ClassCallback<MyClass>( my_class, &MyClass::timer ) ); (*callback)(); // or... callback->call();
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 init(); void push(char); char pop(); int empty(); int full(); void dump_stack(); }; void Stack::init() { top = EmptyStack; } void Stack::push(char c) { if (full()) return; items[++top] = c; } char Stack::pop() { if (empty()) return EmptyFlag; else return items[top--]; } int Stack::full() { if (top + 1 == FullStack) { cerr << "Stack full at " << MaxStack << endl; return true; } else return false; } int Stack::empty() { if (top == EmptyStack) { cerr << "Stack Empty" << endl; return True; } else return False; } void Stack::dump_stack() { for (int i = top; i >= 0; i--) { cout << items[i] << endl; } } and StackTest.cpp #include <iostream> using namespace std; int main() { Stack s; s.init(); s.push('a'); s.push('b'); s.push('c'); cout << s.pop(); cout << s.pop(); cout << s.pop(); } Then I try to compile with: [USER@localhost cs3110]$ g++ StackTest.cpp Stack.cpp StackTest.cpp: In function int main()': StackTest.cpp:8: error:Stack' was not declared in this scope StackTest.cpp:8: error: expected ;' before "s" StackTest.cpp:9: error:s' was not declared in this scope What am I doing wrong?
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. Moreover, you have to define them identically in all of these translation units. In order to satisfy that requirement, class definitions are usually separated into header files (.h files) and included (using #include) into each .cpp file where they are needed. In your case you need to create header file Stack.h, containing the definition of Stack class (and constant definitions in this case) and nothing else 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 init(); void push(char); char pop(); int empty(); int full(); void dump_stack(); }; (Header files also benefint from use of so called include guards, but it will work as shown above for now). This class definition should be moved from Stack.cpp to Stack.h. Instead you will include this .h file into Stack.cpp. Your Stack.cpp will begin as follows #include<iostream> #include "Stack.h" using namespace std; void Stack::init() { top = EmptyStack; } // and so on... The rest of your former Stack.cpp, i.e. member definitions, should remain as is. The Stack.h should also be included into StackTest.cpp, in the same way, so your StackTest.cpp should begin as #include <iostream> #include "Stack.h" using namespace std; // and so on... That's, basically, it. (And instead of providing an init method a better idea would be to create a constructor for the Stack class. But that's a different story).
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. You can try to embed the version info into your library via some static string. On Unix you do not have resources with version information (as on Windows), so this is the only way to do it. Possible approach here can be: a. Create a C/C+ source file (version.cxx) with something like this: #include <version.h> static char version_stamp[]="\n@(#) " PRODUCT " " VERSION " " BUILD_NUMBER; (change format according your needs) b. Create version.h where you define values of PRODUCT/VERSION/BUILD_NUMBER macros. You can generate/modify this header as a part of your build process or modify it manually. E.g.: #define PRODUCT "MyProduct" #define VERSION "1.2.1" #define BUILD_NUMBER "241" c. Make sure that your version C/C++ file (version.cxx) is linked into every library/executable in your product. Modify build tools as needed. Then after you link your library you can use this command to get its version: strings libmy.so | grep '@(#)' If you have SCCS installed on your machine (some Unixes do) you can run: what libmy.so (that's why I used @(#) prefix above) BTW same approach can be used on Windows: just include the header mentioned above into .rc file with version resources defined (and link that .rc into every binary in your product). As result you have one place where you define version and it shared on all platforms and all binaries. Another benefit in (2) is that you may use the version macros from the header above in your run-time code when necessary (e.g. in log files).
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 own result set. In a previous question, I asked if there was any way to make C# mimic the Java randomization function. As a possible solution, without cluttering up the other question, I wanted to know if anyone has had any experience in implementing a "detoured-like" solution.
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 case. Another alternative is to change the implementation at class load time. Basically you rewrite the bytecode of java.util.Random to do something else than what it does by default. The downside of this is that it will affect all instances of java.util.Random, not just the one instance that you might want to change. Then again, most code do not rely on the implementation details of the RNG so this probably isn't an issue. Javassist is quite a nice byte code library. It'll allow you to rewrite byte code at class load time, so you could, e.g. replace the body of the method that produces the random number with a call to your own class that implements the RNG algorithm that you need. You could write a simple class file processor that will be run for the java.util.Random class. The code might be something like this: ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("Random"); // maybe java.util.Random CtMethod m = cc.getDeclaredMethod("nextLong"); m.setBody("my.super.duper.RandomClass.nextLong()"); cc.writeFile();
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 legal since the elements of an STL container need to be assignable. Why is the compiler interpreting (2) to be the same as (3) ?
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 a constant int. Lists of these will compile fine since the pointer itself is still assignable.
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 python and call from C++. Maybe my code can express the thought more clearly than my words: #include <string> #include <iostream> #include <boost/python.hpp> #include <boost/enable_shared_from_this.hpp> using namespace boost::python; using namespace boost; //~ Base Class ClassA class ClassA : public enable_shared_from_this<ClassA> { protected: ClassA(){} public: static shared_ptr<ClassA> create(){ return shared_ptr<ClassA>( new ClassA() ); } virtual void quack(){ std::cout<<"quacks like a ClassA Base"<<std::endl; } }; //~ Wrapper for ClassA struct WrapClassA : public ClassA, wrapper<WrapClassA> { static shared_ptr<WrapClassA> create(){ return shared_ptr<WrapClassA>( new WrapClassA() ); } void quack() { std::cout<<"quacking like a Wrapper..."<<std::endl; if (override f = this->get_override("quack")) { std::cout<<"... override found!"<<std::endl; f(); } else { std::cout<<"... no override found!"<<std::endl; ClassA::quack(); } } void default_quack(){ this->ClassA::quack(); } }; //~ C++ Call Test void quack( shared_ptr<ClassA> ptr ) { ptr->quack(); } //~ Exposing BOOST_PYTHON_MODULE(TestCase) { def( "quack", &quack ); class_<ClassA, shared_ptr<WrapClassA>, noncopyable>( "ClassA", no_init ) .def( "__init__", make_constructor(&WrapClassA::create) ) .def( "quack", &ClassA::quack, &WrapClassA::default_quack ) ; } //~ Main int main() { PyImport_AppendInittab( "TestCase", &initTestCase ); Py_Initialize(); boost::python::object main_module((boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("__main__"))))); boost::python::object main_namespace = main_module.attr("__dict__"); boost::python::object testcase_module( (boost::python::handle<>(PyImport_ImportModule("TestCase"))) ); main_namespace["TestCase"] = testcase_module; FILE* test_file = fopen("test.py", "r"); PyRun_SimpleFile(test_file, "test.py"); fclose( test_file ); std::cin.get(); return 0; } And here's the contents of test.py: print "Testing.." class Derived( TestCase.ClassA ): def __init__( self ): TestCase.ClassA.__init__( self ) def quack( self ): print( "Quacks like a derived class!" ) Ainst = TestCase.ClassA() TestCase.quack( Ainst ) #Should print 'Quacks like ClassA Base' Dinst = Derived() TestCase.quack( Dinst ) #Should print 'Quacks like a derived class!', but doesn't! And the output: Testing... quacking like a Wrapper... ... no override found! quacks like a ClassA Base quacking like a Wrapper... ... no override found! quacks like a ClassA Base So both the base and the class derived in python are acting the same. It looks like it's not finding the override for some reason. I'm not sure but this may have something to do with the create() function. Any ideas would be greatly appreciated! EDIT: Added pythonquack to the py script - This works as expect: def pythonquack( Inst ): print Inst Inst.quack() Calling it for Ainst and Dinst says 'Quacks like a Base', and 'Quacks like a Derived', as I would expect. So for some reason the overrides aren't getting passed back to C++.
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.