question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,494,716
1,494,818
C++ HashTable Object implementation
int hazmat::hashStr(char const * const str) { int count = 0; for ( unsigned i = 0; i < strlen( str ); i++ ) { count += str[i]; // get the ascii sum. } return count % maxSize; }
You are misunderstanding how hash tables work. You need to allocate a fixed-length array (in the simplest case) and then each entry must have a linked list so you can resolve duplicates. That is, two strings may result in the same hash value and you will need to walk the linked list and compare the keys. And yes, like the other poster said, adding characters is a terrible approach. Think about it - "abc" and "cba" will result in the same hash value.
1,495,036
1,495,159
Simple C/C++ network I/O library
I have the following problem to solve. I want to make a number of requests to a number of "remote" servers (actually, a server farm we control). The connection is very simple. Send a line, and then read lines back. Because of the number of requests and the number of servers, I use pthreads, one for each request. The naive approach, using blocking sockets, does not work; very occasionally, I'll have a thread stuck in 'connect'. I cannot use SIGALRM because I am using pthreads. I tried converting the code to O_NONBLOCK but this vastly complicated the code to read single lines. What are my options? I'm looking for the simplest solution that allows the following pseudocode: // Inside a pthread try { req = connect(host, port); req.writeln("request command"); while (line = req.readline()) { // Process line } } catch TimeoutError { // Bitch and complain } My code is in C++ and I'm using Boost. A quick look at Boost ASIO shows me that it probably isn't the correct approach, but I could be wrong. ACE is far, far too heavy-weight to solve this problem.
I saw the comments and i think you can use boost::asio with boost::asio::deadline_timer Fragment of a code: void restart_timer() { timer_.cancel(); timer_.expires_from_now(boost::posix_time::seconds(5)); timer_.async_wait(boost::bind(&handleTimeout, MyClass::shared_from_this(), boost::asio::placeholders::error)); } Where handleTimeout is a callback function, timer_ is boost::asio::deadline_timer and MyClass is similar to class Y: public enable_shared_from_this<Y> { public: shared_ptr<Y> f() { return shared_from_this(); } } You can call restart_timer before connect ou read/write More information about share_from_this()
1,495,549
1,495,576
c++ std vector - invalidated iterator question
I have a standard vector of pointers. Under what circumstances might an iterator into this vector become invalidated? I have reason to believe that when an object is deleted, any vector iterator referencing it is thereby invalidated. This does not seem correct to me, however. I do believe this would be the standard behavior of containers in Managed .NET, but this seems off to me in c++. for (It = Vec.begin(); It != Vec.end(); It++){ GoToOtherCode((*It)); } function GoToOtherCode (ObjectType* Obj){ delete Obj; } Should this invalidate the Iterator It? It doesn't seem to me that it should not, but then I'm stuck with a difficult issue to debug! (I'm scared of my workaround -- to iterate through the vector with via integer-index. (This works fine... I'm just afraid of why the above is causing invalidation issues). Thanks in advance for your time. Edit: Thanks for the advice. The general consensus is that the above code is dangerous, but that it will not invalidate the Iterator. I believe I encountered an error with Visual Studio 2008 debugger, because after opening the project the next day, this invalidate issue was gone. So -- as with many things in computers, if nothing else seems to work, try resetting the thing.
It won't invalidate the iterator, it's actually the way you would delete heap allocated objects that are owned by the vector, the clear() method won't do that for you. This is pretty common: for (It = Vec.begin(); It != Vec.end(); It++) delete *It; Vec.clear(); Perfectly fine if you don't attempt to use what you just deleted.
1,495,649
1,495,698
What is the scope of a namespace alias in C++?
Does a C++ namespace alias defined inside a function definition have a block, function, file, or other scope (duration of validity)?
It's a block duration of validity. E.g If you define a namespace alias as below, the namespace alias abc would be invalid outside {...} block. { namespace abc = xyz; abc::test t; //valid } abc::test t; //invalid
1,495,776
1,514,976
Using pseudo tty with ssh results in warning
I am using ssh from my application and must pass "-t -t" to ssh in order for it to work correctly. Otherwise, the stdin of my application is interfered with by the call to ssh. Forcing a pseudo terminal to ssh via the -t -t avoids this issue, but instead results in the following obscure error message coming back from ssh, although the application seems to work correctly otherwise: tcgetattr: Inappropriate ioctl for device I'd like to get rid of this message to keep it from happening instead of just supressing it, but am not sure why it is coming and what I should do to prevent it. I only get the message when -t -t are passed to ssh. Note a similar question was asked here: http://www.perlmonks.org/?node_id=664789 The man page for ssh says: -t Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g., when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.
One may work around the issue by passing -n to ssh instead of -t -t. From the ssh man page: -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.) So this is another way around the issue of stdin being taken from calling process and given to ssh, however, I'd like to understand how to avoid the warning when using -t -t.
1,495,778
1,495,788
Lambda Expressions and Script Parsing -- Is this a good design idea?
I've written a handful of basic 2D shooter games, and they work great, as far as they go. To build upon my programming knowledge, I've decided that I would like to extend my game using a simple scripting language to control some objects. The purpose is more about the general process of design of writing a script parser / executer than the actual control of random objects. So, my current line of thought is to make use of a container of lambda expressions (probably a map). As the parser reads each line, it will determine the type of expression. Then, once it has decided the type of instruction and discovered whatever values it has to work with, it will then open the map to the kind of expression and pass it any values it needs to work. A more-or-less pseudo code example would be like this: //We have determined somehow or another that this is an assignment operator someContainerOfFunctions["assignment"](whatever_variable_we_want); So, what do you guys think of a design like this?
Not to discourage you, but I think you would get more out of embedding something like Squirrel or Lua into your project and learning to use the API and the language itself. The upside of this is that you'll have good performance without having to think about the implementation. Implementing scripting languages (even basic ones) from scratch is quite a task, especially when you haven't done one before.
1,495,935
1,496,866
QTabWidget tab context menu
I need to display a context menu whenever a tab is clicked on and it needs to react to that specific tab. Is there any way to do this without subclassing it?
Easy way, but possibly not precisely what you need: Connect to the 'currentChanged' signal of your QTabWidget In the slot which is connected to the signal, create a QMenu and populate it as needed Finally, in the slot which is connected to the signal, call QMenu::exec( QCursor::pos() ) This will get a function called whenever the tab is changed (not necessarily clicked) and spawn a menu at the current mouse position. Complicated way, which exactly does what you describe: Call QObject::installEventFilter on your QTabWidget, so that all the events on your QTabWidget are redirected to your own object. In your own object, reimplement QObject::customEvent and handle all QMouseEvent events. Populate a QMenu as needed and call QMenu::exec at the position of the QMouseEvent you're handling.
1,496,284
1,496,780
stepping into MACRO in VC++
I am debugging a source code that has a lot of big #define'd MACRO routines. I am interesting in stepping into them, but I guess, VC++ does not allow step-in functionality ... so, I am converting them into functions, but this is becoming hard for me Is there a way to step into MACRO routines? especially in VC++? PS: I can port the whole code into gcc, if gcc compiler supports stepping into MACRO
In addition to all correct answers above: what I usually do is to show mixed display (C+assembly). This shows what really happens. Even if you are no expert in the underlying assembly, it gives an idea what happens (i.e. is it a trivial replacement or a complex loop). Also it will provide additional opportunities to step into functions. For instance, if your macro is #define foo(a) i++;foo_func(a,i) your debugger will show something like looping and what kind of variables are used). You can use the macro definition as a reference to understand it. 00411454 mov dword ptr [j],eax 00411457 cmp dword ptr [j],0Ah 0041145B jge wmain+58h (411478h) { foo(j); 0041145D mov eax,dword ptr [i] 00411460 add eax,1 00411463 mov dword ptr [i],eax 00411466 mov eax,dword ptr [i] 00411469 push eax 0041146A mov ecx,dword ptr [j] 0041146D push ecx 0041146E call foo_func (411028h) 00411473 add esp,8 } This gives a clue that variables i and j are used to call function foo_func. If you use Visual C++, it will allow you to step into functions called from a macro (F11); not individual statements though.
1,496,318
1,496,470
How to use C++ Classes exported by a dll in Delphi
is there a way to use C++ classes exported by a win32 dll in Delphi for win32? Are there other ways to archieve similar things (COM, .NET, ...)?
You can't import a class. You can only import functions. Rudy Velthuis has written at length on the topic. Although you can't directly use an exported C++ class, he describes a couple of techniques to achieve the same effect: "Flatten" the object, so on the calling side there is no object anymore, just a pointer that gets passed to the DLL along with other parameters for a series of functions that wrap the object's methods. Writing the wrapper is very simple, although it can be tedious. Use pure virtual classes. Windows C++ compilers and Delphi have generally the same VMT layouts, so if the C++ class can be described by a list of pure virtual methods, you can create an equivalent Delphi declaration, do some type-casting with the object pointer returned by the DLL, and proceed. Complete examples of both ways are given in the article.
1,496,453
1,496,703
Uploading to Amazon S3 using cURL/libcurl
I am currently trying to develop an application to upload files to an Amazon S3 bucket using cURL and c++. After carefully reading the S3 developers guide I have started implementing my application using cURL and forming the Header as described by the Developers guide and after lots of trials and errors to determine the best way to create the S3 signature, I am now facing a 501 error. The received header suggests that the method I'm using is not implemented. I am not sure where I'm wrong but here is the HTTP header that I'm sending to amazon: PUT /test1.txt HTTP/1.1 Accept: */* Transfer-Encoding: chunked Content-Type: text/plain Content-Length: 29 Host: [BucketName].s3.amazonaws.com Date: [Date] Authorization: AWS [Access Key ID]:[Signature] Expect: 100-continue I have truncated the Bucket Name, Access Key ID and Signature for security reasons. I am not sure what I'm doing wrong but I think that the error is generating because of the Accept and Transfer-Encoding Fields (Not Really Sure). So can anyone tell me what I'm doing wrong or why I'm getting a 501.
Solved: was missing an CURLOPT for the file size in my code and now everything is working perfectly
1,496,469
1,496,746
Code coverage tools for Symbian C++ and Maemo
What code coverage tools have you used with Symbian C++ and Maemo? What are the pros and cons of the tool you are using?
On Symbian I've used BullseyeCoverage and Testwell CTC++. Cannot really describe the pros/cons of them in detail. Both got the job done, eventually. Both needed some effort with setup and integration with an automated test suite. Both contained bugs that e.g. crashed the downstream compiler with slightly broken instrumented source code. On Maemo, since the toolchain is GCC based, I'd guess gcov would be a good starting point. Though I haven't been working on Maemo much yet and haven't done any coverage measurement there.
1,496,536
1,496,540
how to convert ascii to unsigned int
Is there a method that converts string to unsigned int? _ultoa exists but couldn't find the vise verse version...
std::strtoul() is the one. And then again there are the old ones like atoi().
1,496,731
3,412,249
How do I remove unnecessary resources from my project?
I am working with a very big project (a solution that contains 16 projects and each project contains about 100 files). It is written in C++/C# with Visual Studio 2005. One of the projects has around 2000 resources out of which only 400 are actually used. How do I remove those unused resources? I tried to accomplish the task by searching for used ones. It worked and I was able to build the solution, but it broke at runtime. I guess because enums are used. (IMPORTANT) How can I make sure that it doesn't break at runtime? EDIT: I think one method could be to generate the resource (that is not found) on the fly at runtime (somehow). But I have no idea about ... anything. NOTE: It's okay if a few unnecessary resources are still there.
What I would do is write a custom tool to search your source code. If you remove a resource ID from a header file (i.e. possibly called resource.h) and then recompile and get no warnings: then that's a good thing. Here is how I would go about writing the app. Take as input the resource file (resource.h) you want to scrutinize. Open the header file (*.h) and parse all the resource constants (Or at least the onces you are interested in). Store those in a hash table for quick look up later. For each code file in your project, search the text for instances of each of your resource ID's. When a resource ID is used, increment the value in the hash table otherwise leave it at zero. At the end, dump all the resource ID's that are zero out a log file or something. Then test that indeed you can remove those specified resource ID's safely. Once you do that, then write another tool that removes the specified resource ID's given the results of your log file. You could write such a tool in perl and it would execute in about 0.3 seconds: But would take days to debug. :) Or you could write this in .NET, and it would execute a little slower, but would take you an hour to debug. :)
1,496,930
1,497,033
Using flyweight pattern to share bitmaps between bitmap objects
Hello stack overflowers, I have a desing that uses the flyweight pattern to share bitmaps that are shared between bitmap objects which manage drawing ops, etc. and integrate in the gui library. This is an embedded device so memory is at a premium. Currently I have done a working implementation with a std::vector of auto_ptr of a light class that counts usage. I know this is a bad idea and may leak, so I'm rewriting this part. I'm considering using boost::shared_ptr. The key of my question is that I'd like the bitmaps to be released if there are not being used. If I have a pool of shared_ptr I end up with the used bitmaps loaded once. I'm considering using shared_ptr::use_count() to delete the bitmap if use_count() == 1. But the docs warn against production code of use_count(). Basically the question is flyweight pattern with releasing of individual heavy objects. Do you think there's a better way to do this?
You could use a pool of boost weak pointers so that the pool does not count in the ownership. Only the bitmap objects have boost shared pointers, this way they decide when to release the bitmaps. The pool of weak pointers allows us to retrieve the already constructed bitmaps : When you create a bitmap object you either : get a shared pointer from the weak pointer if it is not empty, or otherwise load the new bitmap, make a new shared pointer from it and insert/replace the weak pointer in the pool. Here is some sample code using a map for the pool : #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <map> #include <string> #include <iostream> // represents the bitmap data class Bitmap { public : Bitmap( std::string const& name ) : name( name ) { std::cout << "Bitmap " << name << std::endl ; } ~Bitmap() { std::cout << "~Bitmap " << name << std::endl ; } std::string name ; }; // the flyweight pool class Factory { public : typedef std::map< std::string , boost::weak_ptr< Bitmap > > Map ; boost::shared_ptr< Bitmap > get( std::string const& what ) { Map::iterator x = map.find( what ); // retrieve existing object from map's weak pointers if( x != map.end() ) { if( boost::shared_ptr< Bitmap > shared = x->second.lock() ) { return shared ; } } // populate or update the map boost::shared_ptr< Bitmap > shared( new Bitmap( what ) ); boost::weak_ptr< Bitmap > weak( shared ); map.insert( std::make_pair( what , weak ) ); return shared ; } private : Map map ; }; int main(int argc, char** argv) { Factory f ; // we try our flyweight bitmap factory ... boost::shared_ptr< Bitmap > a = f.get( "a" ); boost::shared_ptr< Bitmap > b = f.get( "b" ); // a is not made again boost::shared_ptr< Bitmap > a2 = f.get( "a" ); a.reset(); a2.reset(); // a is destroyed before ------ std::cout << "------" << std::endl ; }
1,497,063
1,497,164
Reversing strings in a vector using for_each and bind
I was wandering how it's possible to reverese strings that are contained in a vector using a single for_each command just in one "simple" line. Yea, I know it is easy with a custom functor, but I can't accept, that it can't be done using bind (at least I couldn't do it). #include <vector> #include <string> #include <algorithm> std::vector<std::string> v; v.push_back("abc"); v.push_back("12345"); std::for_each(v.begin(), v.end(), /*call std::reverse for each element*/); Edit: Thanks a lot for those funtastic solutions. However, the solution for me was not to use the tr1::bind that comes with the Visual Studio 2008 feature pack/SP1. I don't know why it does not work like expected but that's the way it is (even MS admits that it's buggy). Maybe some hotfixes will help. With boost::bind everything works like desired and is so easy (but sometimes relly messy:)). I really should have tried boost::bind in the first place...
std::for_each expects a unary function (or at least something with the typedefs of a unary function). std::reverse<> is a binary function. It takes two iterators. It would be possible to bind it all together using boost::bind, but it would be a pretty horrible mess. Something like: boost::bind( &std::reverse<std::string::iterator>, boost::bind(&std::string::begin, _1), boost::bind(&std::string::end, _1)) Better, I think, would be to write a reusable function called reverse_range like so: template <class Range> void reverse_range(Range& range) { std::reverse(range.begin(), range.end()); } (probably with some metaprogramming to ensure that Range& isn't a double-reference) And then use that in your for_each (after adapting it to be a unary function, of course). std::for_each(v.begin(), v.end(), std::ptr_fun(&reverse_range<std::string>)); EDIT: Because string::begin and string::end have both const and non-const variants, it is necessary to cast them (as litb discovered while I was off writing them to test my answer ... +1!). This makes it very verbose. Typedefs can make it a bit more sanitary, but to stick with the one-liner theme: boost::bind( &std::reverse<std::string::iterator>, boost::bind( (std::string::iterator (std::string::*)())&std::string::begin, _1), boost::bind( (std::string::iterator (std::string::*)())&std::string::end, _1) ) ); Which just screams for refactoring. Finally, because I'm bored, bonus points for C++0x: std::for_each(v.begin(), v.end() [](std::string& s){ std::reverse(s); }); EDIT: boost::bind works just fine, no need for boost::lambda.
1,497,068
1,497,163
C++ & GCC: How Does GCC's C++ Implementation Handle Division by Zero?
Just out of interest. How does GCC's C++ implementation handle it's standard number types being divided by zero? Also interested in hearing about how other compiler's work in relation to zero division. Feel free to go into detail. This is not purely for entertainment as it semi-relates to a uni assignment. Cheers, Chaz
It doesn't. What usually happens is that the CPU will throw an internal exception of some sort when a divide instruction has a 0 for the operand, which will trigger an interrupt handler that reads the status of the various registers on a CPU and handles it, usually by converting it into signal that is sent back to the program and handled by any registered signal handlers. In the case of most unix like OSes, they get a SIGFPE. While the behavior can vary (for instance on some CPUs you can tell the CPU not to raise an exception, generally they just put some clamped value in like 0 or MAXINT), that variation is generally due to differences in the OS, CPUm and runtime environment, not the compiler.
1,497,231
1,497,381
How to cast template class ptr to normal class ptr in C++
I have question regarding macros. How could I cast through macro a template class to normal class. In example: #define RUNTIME_CLASS(class_name) ((CRuntimeClass*)(&class##class_name)) template<typename T> A {}; if (RUNTIME_CLASS(A)); I know that this code wouldn't compile because it will not see template bit. But I don't understand the actual macro. the return of it looks like (CRuntimeClass*)(&classA) Why ## concatenate makes class + A ? and how preprocessor understands such notation?
Maybe where you took the macro all the class names are starting with "class" and the macro expects only the second part of the name, what comes after "class".
1,497,278
1,497,318
std::vector and its iterator as single template typename
In order to get an "easier-to-remember" interface to the index-generating function std::distance(a,b), I came up with the idea of a better distinction of it's arguments (when used against the base of a vector: vec.begin() ) by calling a templated function with the vector and its iterator, like: std::vector<MyType> vect; std::vector<MyType>::const_iterator iter; ... ... size_t id = vectorindex_of(iter, vect); with the rationale of never confusing the order of the arguments ;-) The explicit formulation of the above idea would read sth. like template <typename T> inline size_t vectorindex_of( typename std::vector<T>::const_iterator iter, const std::vector<T>& vect ) { return std::distance( vect.begin(), iter ); } ... which works but looks awkward. I'd love to have the template mechanism implicitly deduce the types like (pseudo-code): template <typename T> inline size_t vectorindex_of(T::const_iterator iter, const T& vect) { return std::distance( vect.begin(), iter ); } ... which doesn't work. But why?
The fix is easy: add typename before T::const_iterator iter. This is needed because class templates may be specialized and using typename tells the compiler a type name is expected at T::const_iterator and not a value or something. You do the same in your less generic function, too.
1,497,325
1,497,354
structure in template class
sample code is as follow: struct TEMP { int j; TEMP() { j = 0; } }; template<typename T> class classA { struct strA { long i; strA():i(0) {} }; static strA obj_str; classA(); }; template<typename T> classA<T>::classA() {} template<typename T> classA<TEMP>::strA classA<TEMP>::obj_str; int main() { return 0; } while compiling this code, I am getting following error: test1.cpp:32: internal compiler error: in import_export_decl, at cp/decl2.c:1970 Please submit a full bug report, with preprocessed source if appropriate. See http://bugzilla.redhat.com/bugzilla> for instructions. Preprocessed source stored into /tmp/ccUGE0GW.out file, please attach this to your bugreport. I am building this code at x86_64-redhat-linux machine, and gcc version is gcc version 4.1.2 20070626 (Red Hat 4.1.2-14) Please note this code was already built with gcc version 3.4.5 20051201 (Red Hat 3.4.5-2) at i386-redhat-linux machine. Any idea why this is not able to build with gcc 4.1.2. Thanks in advance.
In any case, your code doesn't make much sense in the following declaration. template<typename T> classA<TEMP>::strA classA<TEMP>::obj_str; Because the T parameter is used nowhere in the declaration. I think you either wanted to write one of the following things: // definition of static member of template template<typename T> typename classA<T>::strA classA<T>::obj_str; // ... or declaration of static member specialization for `T=TEMP` of template template<> classA<TEMP>::strA classA<TEMP>::obj_str; I suspect it was the first one. For the compiler crash - that surely shouldn't happen in any case :) Edit: The bug has already been fixed in 4.4.1 at least - i think there is no need for reporting anymore.
1,497,552
1,497,565
A pointer to abstract template base class?
I cannot figure this out. I need to have an abstract template base class, which is the following: template <class T> class Dendrite { public: Dendrite() { } virtual ~Dendrite() { } virtual void Get(std::vector<T> &o) = 0; protected: std::vector<T> _data; }; Now, I derive from this which specifies exact usage of Dendrite. Now the problem. How do I create a vector of pointers to the base-class with no specific type, which I want to specify by pushing elements to it later? Something like: class Foo { public: ... private: std::vector<Dendrite *> _inputs; //!< Unfortunately, this doesn't work... //! Now I could later on push elements to this vector like //! //! _inputs.push_back(new DeriveFromDendrite<double>()) and //! _inputs.push_back(new DeriveFromDendrite<int>()). }; Is this possible or am I missing something very basic here?
Typically this is done by your template inheriting from an interface class, IE: template <class T> class Dendrite : public IDendrite { public: Dendrite() { } virtual ~Dendrite() { } void Get(std::vector<T> &o) = 0; protected: std::vector<T> _data; }; and then you're IDendrite class could be stored as pointers: std::vector<IDendrite*> m_dendriteVec; However, in your situation, you are taking the template parameter as part of your interface. You may also need to wrap this also. class IVectorParam { } template <class T> class CVectorParam : public IVectorParam { std::vector<T> m_vect; } giving you class IDendrite { ... public: virtual ~IDendrite() virtual void Get(IVectorParam*) = 0; } template <class T> class Dendrite : public IDendrite { ... // my get has to downcast to o CVectorParam<T> virtual void Get(IVectorParam*); };
1,497,753
1,497,884
Debugger Visualizer for non-managed C++ code?
Does anyone know of a C++ IDE or debugger that's supports debugger visualizers for unmanaged C++ code? The problem is that Visual Studio's debugger visaulizer supports only managed C++. Thanks, Olumide PS: I'm still open to using VS if I can find a technique for making the visualizer work with unmanaged C++.
Are the custom visualizers in Visual Studio 2005+ (basically editing autoexp.dat) what you need?
1,497,913
1,500,165
How different is Qt4 from Qt3?
I used to program in Qt3 a long time ago and I had read a great book that I still have by O'reilly on Qt3. I wanted to start using Qt4 again now several years later. Can I use my Qt3 book to get up to speed again, or has things changed so much that I should buy a Qt4 book?
In a nutshell: Qt 4 is (even) better -- and more powerful and flexible -- than Qt 3 you'll be fine! The Porting to Qt 4 documentation gives some idea of the many small changes to APIs. What's New in Qt 4 gives an overview of the big differences between Qt 3 and Qt 4. Some major changes that noone has mentioned so far: Model/View architecture template container classes a new, modular build system a new action-based main window implementation widget styling with CSS ports for S60 and other platforms There are also lots of small fixes, improvements and useful new classes such as QFormLayout and QSignalSpy.
1,498,211
1,594,732
overriding GetSecurityId in IInternetSecurityManager
I have built an executable which launches a dialog box in which is embedded the IE web browser active-x control (C++). I want this control to allow cross site scripting. One frame on the web page loads local html, the other loads from a server. I then want the server page to call a javascript function that lives in the local html file. I am trying to achieve this by having the control implement it's own "IInternetSecurityManager" interface in which I am providing my own ProcessUrlAction and GetSecurityId methods. From what I've read, what I need to do is make GetSecurityId return the same domain for all urls. My custom implementations are getting called, but no matter what I do, I get the "Permission denied" error when the server html tries to access script on the local html file. Below are my implementations. Does anyone see anything wrong? #define SECURITY_DOMAIN "http:www.mysite.com" STDMETHOD (GetSecurityId)( LPCWSTR pwszUrl, BYTE *pbSecurityId, DWORD *pcbSecurityId, DWORD_PTR dwReserved) { if (*pcbSecurityId >=512) { memset(pbSecurityId,0,*pcbSecurityId); strcpy((char*)pbSecurityId,SECURITY_DOMAIN); pbSecurityId[strlen(SECURITY_DOMAIN)] = 3; pbSecurityId[strlen(SECURITY_DOMAIN)+1] = 0; pbSecurityId[strlen(SECURITY_DOMAIN)+2] = 0; pbSecurityId[strlen(SECURITY_DOMAIN)+3] = 0; *pcbSecurityId = (DWORD)strlen(SECURITY_DOMAIN)+4; return S_OK; } return INET_E_DEFAULT_ACTION; } STDMETHOD(ProcessUrlAction)( /* [in] */ LPCWSTR pwszUrl, /* [in] */ DWORD dwAction, /* [size_is][out] */ BYTE __RPC_FAR *pPolicy, /* [in] */ DWORD cbPolicy, /* [in] */ BYTE __RPC_FAR *pContext, /* [in] */ DWORD cbContext, /* [in] */ DWORD dwFlags, /* [in] */ DWORD dwReserved) { DWORD dwPolicy=URLPOLICY_ALLOW; if ( cbPolicy >= sizeof (DWORD)) { *(DWORD*) pPolicy = dwPolicy; return S_OK; } return INET_E_DEFAULT_ACTION; }
By delegating these functions to the normal security manager and having a look at the structures the normal security manager fills in, I was able to determine that my issue was in GetSecurityId. For my purposes, I wanted to set the security domain to be a local file for all comers. #define SECURITY_DOMAIN "file:" if (*pcbSecurityId >=512) { memset(pbSecurityId,0,*pcbSecurityId); strcpy((char*)pbSecurityId,SECURITY_DOMAIN); pbSecurityId[strlen(SECURITY_DOMAIN)+1] = 0; pbSecurityId[strlen(SECURITY_DOMAIN)+2] = 0; pbSecurityId[strlen(SECURITY_DOMAIN)+3] = 0; pbSecurityId[strlen(SECURITY_DOMAIN)+4] = 0; *pcbSecurityId = (DWORD)strlen(SECURITY_DOMAIN)+4; }
1,498,283
1,498,355
How to obtain Windows special paths for a user account from a service
I want to be able to retrieve Windows "special paths" (e.g. temporary files folder, desktop) for user accounts, but from a service. I know the normal way to do this is by using SHGetFolderPath with the appropriate CSIDL for the folder type. Is there any way to get this type of info for each user without the service having to log in as each user in turn?
I'm no expert on this, but it seems you can use the hToken argument to SHGetFolderPath to pass in another user's token. I think you can create such a token using impersonation. If that does not work: these folders are in the registry under HKEY_USERS/<user's-sid>/Software/Microsoft/Windows/CurrentVersion/Explorer/Shell Folders. How to get the SID is explained in this question. It's in C# but I think it'll actually be easier in C++.
1,498,714
1,498,753
Why compiler provides default copy constructor
I wanted to know Why compiler provides default copy constructor..Whats the strategy behind that idea. Thanks in Advance.
From a related (but not same) question - Why don't C++ compilers define operator== and operator!=?: Stroustrup said this about the default copy constructor in "The Design and Evolution of C++" (Section 11.4.1 - Control of Copying): I personally consider it unfortunate that copy operations are defined by default and I prohibit copying of objects of many of my classes. However, C++ inherited its default assignment and copy constructors from C, and they are frequently used. So the answer is that it was included reluctantly by Stroustrup for backwards compatibility with C (probably the cause of most of C++'s warts, but also probably the primary reason for C++'s popularity). For my own purposes, in my IDE the snippet I use for new classes contains declarations for a private assignment operator and copy constructor so that when I gen up a new class I get no default assignment and copy operations - I have to explicitly remove the declaration of those operations from the private: section if I want the compiler to be able to generate them for me.
1,498,766
1,498,802
C++ call virtual method in child class
i have the following classes: class A { protected: A *inner; public: .... virtual void doSomething() = 0; .... } class B: public A { ... void doSomething() { if(inner != NULL) inner->doSomething(); } ... } When I use inner->doSomething() I get a segmentation fault. What should I do in order to call inner->doSomething() in the B class? thanks in advance.
Without an explicit initialization of the member inner, it's possible for it to be both not NULL and point to invalid memory. Can you show us the code that explicitly initalizes inner? An appropriate constructor for A would be the following protected: A() : inner(NULL) { ... }
1,498,874
1,499,036
Why is this an "overloading ambiguity" in gcc?
Why is this an error : ie. arent long long and long double different types ? ../src/qry.cpp", line 5360: Error: Overloading ambiguity between "Row::updatePair(int, long long)" and "Row::updatePair(int, long double)". Calling code: . . pRow -> updatePair(924, 0.0); pRow -> updatePair(925, 0.0); .
$1 $2 Row::updatePair(int, long long) // #1 Row::updatePair(int, long double) // #2 // updatePair(924, 0.0); // int -> int (#1) // $1#1 // int -> int (#2) // $1#2 // // double -> long long // $2#1 // double -> long double // $2#2 In this case, both conversions in the first group are exact matches, while both conversions in the second group are conversions. They are equally ranked - it's like int -> long vs int -> double. The other call has the same types, just different values, so it exhibits the same behavior. Only float -> double is a promotion, like only integer types smaller than int to int (and for some exotic platforms to unsigned int) are promotions. So the following wouldn't be ambiguous $1 $2 Row::updatePair(int, double) // #1 Row::updatePair(int, long double) // #2 // updatePair(924, 0.0f); // int -> int (#1) // $1#1 // int -> int (#2) // $1#2 // // float -> double // $2#1 (promotion - not a ranked as conversion). // float -> long double // $2#2 In that case, the second argument has a better conversion sequence when converted to the parameter of #1.
1,498,949
1,499,377
Data structure for fast line queries?
I know that I can use a KD-Tree to store points and iterate quickly over a fraction of them that are close to another given point. I'm wondering whether there is something similar for lines. Given a set of lines L in 3D (to be stored in that data structure) and another "query line" q, I'd like to be able to quickly iterate through all lines in L that "are close enough" to q. The distance I'm planning to use is the minimal Euclidean distance between two points u and v where u is some point on the first line and v is some point on the second line. Computing that distance is not a problem (there's a nice trick involving the cross product). Maybe you guys have a good idea or know where to look for papers, descriptions, etc... TIA, s.
Another option - and the most commonly used one for spatial indexing in disk-based database systems - is the R-Tree. It's a bit more complicated to implement than a KD-Tree, but it's generally considered to be faster, and has no problem indexing lines and polygons.
1,499,024
1,499,061
How to create native DLL in Visual Studio from C# code?
I have the source code of a C# program. I want to create a DLL out of it which I want to use in C++. Is it possible to create a native DLL in Visual Studio 2008 which can be used in C++?
If you want the program to be native, and not managed, you'll need to port it to C++, instead of using C#. That being said, you can compile it in C# into a library, and use it from C++ by using C++/CLI. This just requires that you compile the files that use the C# library with the /clr flag. This provides C++ access to the .NET framework, and lets you use libraries made in C# directly from C++. Alternatively, you can use .NET's COM interop to expose the C# class(es) as COM objects, and then use those from native C++.
1,499,079
1,499,100
Communicate between AIR(Flex) and C++ Applications
I need to be able to communicate between two applications that reside on the same machine. One is using Flex and the other is in C++. I would like to be able to call functions and pass arguments to each other. What is the best way to communicate between them? I was thinking about using sockets.
As for now yes, you'll need to use sockets. AIR 2.0 will provide access to native processes, but that will require a native (per OS) installer. More info: http://www.mikechambers.com/blog/2009/09/22/fotb-slides-advanced-desktop-development-with-adobe-air/
1,499,086
2,686,833
POCO C++ - NET SSL - how to POST HTTPS request
How to correctly do a POST to HTTPS server and embed the login data correctly. Below code does not return any cookies (in Wininet it does). I wonder how POCO HTTP library handles HTTP redirections? MyApp() { try { const Poco::URI uri( "https://localhost.com" ); const Poco::Net::Context::Ptr context( new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "rootcert.pem" ) ); Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context ); Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, "/login.php" ); req.setContentType("Content-Type: application/x-www-form-urlencoded\r\n"); req.setKeepAlive(true); std::string reqBody("username=???&password=???&action_login=Log+In\r\n\r\n"); req.setContentLength( reqBody.length() ); //Poco::Net::HTTPBasicCredentials cred("???", "???"); //cred.authenticate(req); session.sendRequest(req) << reqBody; Poco::Net::HTTPResponse res; std::istream& rs = session.receiveResponse(res); std::string resp; std::vector<Poco::Net::HTTPCookie> cookies; res.getCookies( cookies ); } catch( const Poco::Net::SSLException& e ) { std::cerr << e.what() << ": " << e.message() << std::endl; } catch( const std::exception& e ) { std::cerr << e.what() << std::endl;; } };
You are setting content type like this: req.setContentType("Content-Type: application/x-www-form-urlencoded\r\n"); which should be: req.setContentType("application/x-www-form-urlencoded\r\n");
1,499,156
1,499,591
convert astronomically large numbers into human readable form in C/C++
My program prints out HUGE numbers - like 100363443, up to a trillion -- and it sort of hard to read them, so I would like to print any number in easy to read form. right now I use printf ("%10ld", number); format I would appreciate a resulting number using printf. Most of my code is c++ yet I don't want to introduce std::cout, as I already have printf thanks
Use the non-standard apostrophe flag in the printf format string, if you have that option available and don't mind losing a little bit of portability. According to my documentation, the ' flag is available for POSIX systems since 1997. If you are on Unix, Linux, Mac, ... you should have no problem If you are on Windows, DOS, iSeries, Android, ... all bets are off (but maybe you can install a POSIX layer to your system). #include <locale.h> #include <stdio.h> int main(void) { long int x = 130006714000000; setlocale(LC_NUMERIC, "en_US.utf-8"); /* important */ while (x > 0) { printf("# %%'22ld: %'22ld\n", x); /* apostrophe flag */ x *= 2; /* on my machine, the Undefined Behaviour for overflow // makes the number become negative with no ill effects */ } return 0; } On my system this program produces: # %'22ld: 130,006,714,000,000 # %'22ld: 260,013,428,000,000 # %'22ld: 520,026,856,000,000 # %'22ld: 1,040,053,712,000,000 # %'22ld: 2,080,107,424,000,000 # %'22ld: 4,160,214,848,000,000 # %'22ld: 8,320,429,696,000,000 # %'22ld: 16,640,859,392,000,000 # %'22ld: 33,281,718,784,000,000 # %'22ld: 66,563,437,568,000,000 # %'22ld: 133,126,875,136,000,000 # %'22ld: 266,253,750,272,000,000 # %'22ld: 532,507,500,544,000,000 # %'22ld: 1,065,015,001,088,000,000 # %'22ld: 2,130,030,002,176,000,000 # %'22ld: 4,260,060,004,352,000,000 # %'22ld: 8,520,120,008,704,000,000
1,499,182
1,499,256
Fastest way to share a connection and data from it with multiple processes?
I have multiple app processes that each connect to servers and receive data from them. Often the servers being connected to and the data being retrieved overlaps between processes. So there is a lot of unnecessary duplication of the data across the network, more connections than should be necessary (which taxes the servers), and the data ends up getting stored redundantly in memory in the apps. One solution would be to combine the multiple app processes into a single one -- but for the most part they really are logically distinct, and that could be years of work. Unfortunately, latency is critically important, and the volume of data is huge (any one datum may not be too big, but once a client makes a request the server will send a rapid stream of updates as the data changes, which can be upwards of 20MB/s, and these all need to be given to the requesting apps with the shortest possible delay). The solution that comes to mind is to code a local daemon process, that the app processes would request data from. The daemon would check if a connection to the appropriate server already exists, and if not make one. Then it would retrieve the data and using shared memory (due to latency concern, otherwise I'd use sockets) give the data to the requesting app. A simpler idea in the short term that would only solve the redundant connections would be to use unix domain sockets (this will run on a unix OS, though I prefer to stick to crossplatform libs when I can) to share a socket descriptor between all the processes, so they share a single connection. The issue with this is consuming the buffer -- I want all the processes to see everything coming over the socket, and if I understand right with this approach a read in one process on the socket will prevent other processes from seeing the same data on their next read (the offset within the shared descriptor will be bumped).
I believe a dedicated service that exposes the data via shared memory is your best bet. Secondary from that would be a service that multicasts the data via named pipes, except that you're targeting a Unix variant and not Windows. Another option would be UDP multicast, so that the data replication occurs at the hardware or driver level. The only problem is that UDP data delivery is not guaranteed to be in order, nor is it guaranteed to deliver at all. I think sharing the physical socket is a hack and should be avoided, you would be better off implementing a driver that did what you wanted the daemon to do transparently (e.g. processes saw the socket as a normal socket except internally the socket was mapped to a single socket, where logic existed to re-broadcast the data among the virtual sockets.) Unfortunately the level of effort to get it right would be significant, and if time to complete is a concern sharing the socket isn't really a good route to take (whether done at the driver level, or via some other hacky means such as sharing the socket descriptor cross-process.) Sharing the socket also assumes that it is a push-only connection, e.g. no traffic negotiation is ocurring at the app level (requests for data, for example, or acknowledgements of data receipt.) A quick-path to completion may be to look at projects such as BNC and convert the code, or hijack the general idea, to do what you need. Replicating traffic to local sockets shouldn't incur a huge latency, though you would be exercising the NIC (and associated buffers) for all of the data replication and if you are nearing the limit of the hardware (or have a poor driver and/or TCP stack implementation) then you may wind up with a dead server. Where I work we've seen data replication tank a gigabit ether card at the driver level, so it's not unheard of. Shared Memory is the best bet if you want to remain platform independent, and performant, while not introducing anything that may become unsupportable in 5 years time due to kernel or hardware/driver changes.
1,499,217
1,501,077
Boost Graph as basis for a simple DAG Graph?
I'm looking at using Boost Graph Library as the basis for a dag graph. I haven't really used it all that much before, so not too familiar with how it works. Although I don't need edge weights and clever traversing algorithms, I would quite like to get the serialisation for free, plus the constraints enforcing dag graphs and disallowing parallel arcs. Planning on abstracting the complexities of the BGL, but is this overkill for this kind of thing, as I'll only be selecting a node and recursing over all of its children? I would also like to be able to have isolated nodes that aren't connected to other nodes in the graph, but still be able to iterate over these in the graph. Is this something that is provided, or would I have to store my own collection of nodes?
Iteration over nodes in a graph is provided. There's an interface that returns a begin, end pair of iterators over the nodes (and a similar one over the edges): std::pair<vertex_iterator, vertex_iterator> vertices(const adjacency_list& g) From the documentation
1,499,293
1,569,705
Input Method Editor windows return FALSE for WM_QUERYENDSESSION - why?
We have a bizarre and very infrequent issue where people can't log off the Windows server when our product is running. The system is multi-application, all MFC/C++. The apps are run from a management service so they survive logoff. It's been running fine for donkeys years in loads of installations around the world. I wrote a test application to enumerate all windows, send them a WM_QUERYENDSESSION message, and stop when it returns FALSE. This test is being run on one of these rare case where the problem repros, in Germany. It always seems to be an invisible IME (Input Method Editor) window which is the guilty party, but the IME window always belongs to one of our MFC applications. I think I can solve the problem for an individual application by calling ImmDisableIME (-1). But what I'm looking for is... (a) if someone has a configuration method to get around this so we don't have to modify all the versions of all the applications for all the countries - a large job. (b) Why this should happen in the first place. Why should an IME window we didn't create decide that the user can't log off? (c) Has anyone else ever seen this before? Misery loves company, you know. As stated, currently it's happening on one machine in Germany. Of course we can't repro here, on any version of Windows. Bah.
It would seem that Microsoft have encountered some of these problems with various versions of the IME. I found some relatively old updates. What OS is your customer running and do they have version(s) of Office installed? Is it possible to determine the filename and version of the module creating the IME window in your case? Here is an update related to the IME from Office 2003: Microsoft Known Bug 870774 The message box takes 30 seconds to close when you shutdown Windows When you try to shutdown a Japanese Windows 2000-based computer that has the Office 2003 framework that is used to support advanced text services installed without first closing all your open programs, you receive a message box for each open program. When you click End, it takes approximately 30 seconds to close each message box before Windows can shutdown. File name Version ----------------------- Msctf.dll 5.1.2409.39 Msimtf.dll 5.1.2409.39 Input.cpl 5.1.2409.39 Sptip.dll 5.1.2409.39 Here is an update which relates to the Windows XP IME: Microsoft Known Bug 811147 Windows Messenger Hangs During Shutdown and a Terminate Program Dialog Box Appears Date Time Version Size File name ---------------------------------------------------- 17-Jan-2003 15:36 8.1.4008.0 57,400 Cplexe.exe 17-Jan-2003 15:34 8.1.4008.0 335,917 Imjp81.ime 06-Feb-2003 13:56 8.1.4008.0 827,438 Imjp81k.dll 06-Feb-2003 13:56 8.1.4008.0 360,494 Imjpcic.dll 06-Feb-2003 13:56 8.1.4008.0 716,857 Imjpcus.dll 06-Feb-2003 13:56 8.1.4008.0 81,977 Imjpdct.dll 22-Jan-2003 09:52 8.1.4008.0 307,258 Imjpdct.exe 17-Jan-2003 15:36 8.1.4008.0 155,706 Imjpdsvr.exe 17-Jan-2003 15:36 196,666 Imjpinst.exe 17-Jan-2003 15:36 8.1.4008.0 208,953 Imjpmig.exe 17-Jan-2003 15:36 8.1.4008.0 233,528 Imjprw.exe 17-Jan-2003 15:36 8.1.4008.0 262,201 Imjputy.exe 06-Feb-2003 13:56 8.1.4008.0 274,490 Imjputyc.dll 14-Nov-2002 10:01 5.3.10.0 4,608 Spmsg.dll
1,499,512
1,499,838
Installing Boost libraries on Snow Leopard
I have followed the directions on the boost website. I have put the boost dir in the path. I still cannot compile a C++ program using the boost libraries. I am specifically trying to use the filesystem library. Any help is greatly appreciated. --TJB
Did you compile the filesystem library? Many Boost libraries are header-only, but filesystem is one of the few that have to be compiled (and linked). Instructions on how to do that can be found at points 5 and 6 of the Getting Started on Unix Variants page. Instructions specific to the filesystem lib are at http://www.boost.org/doc/libs/1_40_0/libs/filesystem/doc/index.htm#Building
1,499,569
1,510,406
How do I define a SWIG typemap for a reference to pointer?
I have a Publisher class written in C++ with the following two methods: PublishField(char* name, double* address); GetFieldReference(char* name, double*& address); Python bindings for this class are being generated using SWIG. In my swig .i file I have the following: %pointer_class(double*, ptrDouble); This lets me publish a field that is defined in a Python variable: value = ptrDouble() value.assign(10.0) PublishField("value", value.cast()) Trying to using the GetFieldReference method results in a TypeError however: GetFieldReference("value", newValue) I think I need to create a typemap for the double*& that returns a ptrDouble, but I am not quite sure what that would look like.
Here is a working solution that I came up with. Add a wrapper function to the swig.i file: %inline %{ double * GetReference(char* name, Publisher* publisher) { double* ptr = new double; publisher->GetFieldReference(name, ptr); return ptr; } %} Now from Python I can use the following: value = ptrDouble.frompointer(GetFieldReference("value", publisher)
1,499,688
1,508,357
Utf-8 in c++: quick & dirty tricks
I am aware that there are been various questions about utf-8, mainly about libraries to manipulate utf-8 'string' like objects. However, I am working on an 'internationalized' project (a website, of which I code a c++ backend... don't ask) where even if we deal with utf-8 we don't acutally need such libraries. Most of the times the plain std::string methods or STL algorithms are very sufficient to our needs, and indeed this is the goal of using utf-8 in the first place. So, what I am looking for here is a capitalization of the "Quick & Dirty" tricks that you know of related to utf-8 stored as std::string (no const char*, I don't care about c-style code really, I've got better things to do than constantly worrying about my buffer size). For example, here is a "Quick & Dirty" trick to obtain the number of characters (which is useful to know if it will fit in your display box): #include <string> #include <algorithm> // Let's remember than in utf-8 encoding, a character may be // 1 byte: '0.......' // 2 bytes: '110.....' '10......' // 3 bytes: '1110....' '10......' '10......' // 4 bytes: '11110...' '10......' '10......' '10......' // Therefore '10......' is not the beginning of a character ;) const unsigned char mask = 0xC0; const unsigned char notUtf8Begin = 0x80; struct Utf8Begin { bool operator(char c) const { return (c & mask) != notUtf8Begin; } }; // Let's count size_t countUtf8Characters(const std::string& s) { return std::count_if(s.begin(), s.end(), Utf8Begin()); } In fact I have yet to encounter a usecase when I would need anything else than the number of characters and that std::string or the STL algorithms don't offer for free since: sorting works as expected no part of a word can be confused as a word or part of another word I would like to know if you have other comparable tricks, both for counting and for other simple tasks. I repeat, I know about ICU and Utf8-CPP, but I am not interested in them since I don't need a full-fledged treatment (and in fact I have never needed more than the count of characters). I also repeat that I am not interested in treating char*'s, they are old-fashioned.
Well this dirty trick will not work. First, what is the value of mask after this: const unsigned char mask = 0x11000000; const unsigned char notUtf8Begin = 0x10000000; Perhaps you are mixing hex representation with binary. Second, as you correctly say in utf-8 encoding, a character may be several bytes long. std::count_if will iterate through all bytes in a UTF8 sequence. But what you actually need is to look at leading byte for every character and skip the rest until the next character comes. It will not be hard to implement a single cycle which does the calculation and jumping forward using the simple mask table for leading bytes. At the end you get the same O(n) for checking the characters and it will work with every UTF8 string.
1,499,878
1,514,439
Use a Graph Library/Node Network Library or Write My Own?
I'm trying to decide between going with a pre-made graph/node network library or to roll my own. I'm implementing some graph search algorithms which might require some significant customization to the class structure of the node and/or edges. The reason I'm not sure what to do is that I'm unsure if customization of a pre-made might be more expensive/trouble than making my own in the first place. I'm also curious, but less so, of the performance trade-offs. Is there anyone out there have direct experience with using one of the libraries out there and have advice based on a success or failure story? I want to hear the worst so that whatever I chose, I know what I'm getting into. There are only two that I've found in my search so far: The Boost Graph Library (BGL) and GOBLIN. Specific advice on either of these, or suggestions for others is greatly appreciated as well. BGL seems pretty damn arcane. Is it worth struggling through?
I can perhaps provide a little guidance on the BGL. The library is very flexible. The cost of this is that the syntax can be very baroque, in order to accommodate all the possibilities. However, it is sufficiently flexible that simple things can be done simply. Unfortunately the boost documentation goes at things full tilt, providing a description only of the full complexity, without a hint of how simple things can be. ( "Any sufficiently advanced technology is indistinguishable from magic" - Arthur C. Clarke. What he should have said is "Any advanced technology, sufficiently badly documented, is indistinguishable from magic ) Consider: typedef property_map<Graph, vertex_index_t>::type IndexMap; IndexMap index = get(vertex_index, g); typedef graph_traits<Graph>::vertex_iterator vertex_iter; std::pair<vertex_iter, vertex_iter> vp; for (vp = vertices(g); vp.first != vp.second; ++vp.first) { std::cout << index[*vp.first] << " "; } This is how the "quick tour" suggests we print out a list of the graph vertices. However, a little study shows that a vertex is no more than an integer index, and the code can be greatly simplified to for (int v = *vertices(g).first; v != *vertices(g).second; ++v) std::cout << v << " "; Perhaps there are some magical things that cannot be achieved with this simplified code, but for every day use it reasonable to drastically prune the syntax that encrust BGL so you can see what your are coding. Sometimes the elaborate syntax cannot be removed. ( Or perhaps I have just not noticed the underlying truth ). Then I usually use a little utility function to encapsulate the complexity abd keep it away from the algorithm I am working on. For example, I often need to loop over the children of a vertex vector<int> getVertexChildren( int v ) { vector<int> vc; typedef std::pair<graph_traits<graph_t>::out_edge_iterator, graph_traits<graph_t>::out_edge_iterator> out_edge_iter_pair_t; for( out_edge_iter_pair_t ep = out_edges(v,m_tree); ep.first != ep.second; ++(ep.first)) { vc.push_back( target( *ep.first, m_tree ) ); } return vc; } #define FOR_ALL_CHILDREN( v ) vector<int> vc=getVertexChildren(v); BOOST_FOR_EACH( int child, vc ) The bottom line is: go ahead and use BGL. It can be simplified to do simple things, but once you have learned to use it, all the immense flexibility will be available whenever you do need it.
1,499,884
1,500,006
Sphere online judge finds my code wrong although its working correct for hundreds of test cases
Question goes like this.. Input n [the number of multiplications <= 1000] l1 l2 [numbers to multiply (at most 10000 decimal digits each)] Text grouped in [ ] does not appear in the input file. Output The results of multiplications. My code.. #include<iostream> #include<vector> using namespace std; int main() { long int n,a,b,c,t; vector<long int> v(1000); vector<long int>::iterator p; cin>>n; t=n; p=v.begin(); while(t>0) { cin>>a; cin>>b; *p=a; *(p+1)=b; p+=2; t--; } t=n; p=v.begin(); while(t>0) { c= (*p) * (*(p+1)); cout<<"\n"<<c; p+=2; t--; } return 0; }
Had to google your problem to understand what it was: here it is, please be considerate of your readers :x Your code cannot actually work: long int is not long enough (and this is implementation dependent anyway) You will have to read the integers 'char' by 'char' and roll your own implementation of BigInts which is the difficulty of the problem here I surmise. Furthermore, you will have to deal with overflow: the result of int x int might not fit into an int. Truth to be told, you should be prepared to have a result that might take up to 20.000 digits
1,500,064
1,500,131
Renaming first and second of a map iterator
Is there any way to rename the first and second accessor functions of a map iterator. I understand they have these names because of the underlying pair which represents the key and value, but I'd like the iterators to be a little more readable. I think this might be possible using an iterator adaptor, but I'm not sure how to implement it. Please note that I can't use boost. Example of what I mean: map<Vertex, Edge> adjacency_list; for(map<Vertex, Edge>::iterator it = adjacency_list.begin(); it != adjacency_list.end(); ++it) { Vertex v = it->first; //instead I would like to have it->vertex }
If you're just concerned about readability you could do something like this: typedef map<Vertex, Edge> AdjacencyList; struct adjacency { adjacency(AdjacencyList::iterator& it) : vertex(it->first), edge(it->second) {} Vertex& vertex; Edge& edge; }; And then: Vertex v = adjacency(it).vertex;
1,500,230
1,501,042
Is there a way to create a view in a CSplitterWnd without using (MFC) dynamic object creation?
I was previously using a CSplitterWnd in a MFC application, using it's CreateView function. Everything was working fine but now I would like to pass a parameter to the constructor of my views, so I cannot use MFC dynamic object creation (DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE) because they require an empty constructor. After searching a little on the internet I found an exemple that looks like this: m_wndSplitter.CreateView(0,0,RUNTIME_CLASS(CMyView), CSize(0,0), pContext); m_wndSplitter.CreateView(0,1,RUNTIME_CLASS(CMyView), CSize(0,0), pContext); m_pView0=(CMyView *)m_wndSplitter.GetPane(0,0); m_pView1=(CMyView *)m_wndSplitter.GetPane(0,1); This could be a workaround (i.e.: create a new function in CMyView letting me specify what I want) but this would be ugly and error prone. Anyone know if there is another way I could do this? Edit: Adding more details after ee's answer: Your right that the initialize method would work but this force me to remember to call that initialize method, but like you pointed out I will probably not create these views many times so that should be ok. Another thing I would maybe like is to manage the lifetime of the view myself so again this is not possible using CreateView. Thanks
After checking Javier De Pedro's answer I though I could override the creation function so I did (semi-pseudo-code): class ObjGetter { static CObject* obj; public: ObjGetter(CObject* obj_){obj = obj_;} static CObject* __stdcall getObj() { return obj; } }; CObject* ObjGetter::obj = NULL; BOOL CMyFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { //... myView = new CMyView(NULL); CRuntimeClass rt(*myView->GetRuntimeClass()); ObjGetter objGetter(myView); rt.m_pfnCreateObject = &ObjGetter::getObj; m_wndSplitter.CreateView(0,0, &rt, CSize(0,0), pContext); } Now this work but there is the problem that it will destroy my class when closing and I said I would maybe want to track memory myself so I overloaded PostNcDestroy in CMyView to do nothing instead of calling delete this: CMyView::PostNcDestroy(){} Now it should prevent it from getting deleted but now it crash when exiting so I overriden CMyFrame::OnClose like this: void CMyFrame::OnClose() { m_wndSplitter.DeleteView(0, 0); delete myView; myView = NULL; //seems to be needed to be deleted before //CFrameWnd::OnClose or it crash CFrameWnd::OnClose(); } Now theorically I should be able to keep the myView pointer elsewhere as long as I delete it before the document exit. Thanks for your help guys.
1,500,349
1,500,358
Is there a faster and object orientated alternative to SDL for C++?
The current version of libsdl (1.2.x branch) is very, very slow with blending and per pixel alpha (as it uses software blending). Is there any other good alternative to it?
SFML is exactly what you need: http://sfml-dev.org/. Skim through the tutorials, you'll see that it's way easier and more powerful than SDL.
1,500,363
1,500,517
Compile time sizeof_array without using a macro
This is just something that has bothered me for the last couple of days, I don't think it's possible to solve but I've seen template magic before. Here goes: To get the number of elements in a standard C++ array I could use either a macro (1), or a typesafe inline function (2): (1) #define sizeof_array(ARRAY) (sizeof(ARRAY)/sizeof(ARRAY[0])) (2) template <typename T> size_t sizeof_array(const T& ARRAY){ return (sizeof(ARRAY)/sizeof(ARRAY[0])); } As you can see, the first one has the problem of being a macro (for the moment I consider that a problem) and the other one has the problem of not being able to get the size of an array at compile time; ie I can't write: enum ENUM{N=sizeof_array(ARRAY)}; or BOOST_STATIC_ASSERT(sizeof_array(ARRAY)==10);// Assuming the size 10.. Does anyone know if this can be solved? Update: This question was created before constexpr was introduced. Nowadays you can simply use: template <typename T> constexpr auto sizeof_array(const T& iarray) { return (sizeof(iarray) / sizeof(iarray[0])); }
Try the following from here: template <typename T, size_t N> char ( &_ArraySizeHelper( T (&array)[N] ))[N]; #define mycountof( array ) (sizeof( _ArraySizeHelper( array ) )) int testarray[10]; enum { testsize = mycountof(testarray) }; void test() { printf("The array count is: %d\n", testsize); } It should print out: "The array count is: 10"
1,500,495
1,544,722
How to build wxmathPlot for win32?
I downloaded the latest wxmathplot but the readme is a bit sparse with instructions on how to build on win32 platform. Has anyone used this library for win32? Can someone point me to the docs or give some hints/advice on how to build for win32 targets. We'll eventually use this for cross platform stuff, for now it is just win32 until we port our other code. I presume I have to use CMake, but have not used it before and it is not obvious to me how to build this all - I have already installed CMake, but I am apparently too stupid to figure out how to build this library/samples. Well, I managed to make an SLN file, but it was not obvious.
I use wxMathPlot. I simply add mathplot.cpp and mathplot.h to the MSVS2008 C++ projects that need to use it. This compiles and links without my having to do anything special.
1,500,584
1,500,912
Performance difference between C++ and C# for mathematics
I would like to preface this with I'm not trying to start a fight. I was wondering if anyone had any good resources that compared C++ and C# for mathematically intensive code? My gut impression is that C# should be significantly slower, but I really have no evidence for this feeling. I was wondering if anyone here has ever run across a study or tested this themselves? I plan on running some tests myself, but would like to know if anyone has done this in a rigorous manner (google shows very little). Thanks. EDIT: For intensive, I mean a lot of sin/cos/exp happening in tight loops
I have to periodically compare the performance of core math under runtimes and languages as part of my job. In my most recent test, the performance of C# vs my optimized C++ control-case under the key benchmark — transform of a long array of 4d vectors by a 4d matrix with a final normalize step — C++ was about 30x faster than C#. I can get a peak throughput of one vector every 1.8ns in my C++ code, whereas C# got the job done in about 65ns per vector. This is of course a specialized case and the C++ isn't naive: it uses software pipelining, SIMD, cache prefetch, the whole nine yards of microoptimization.
1,500,653
1,500,693
C++ Templates type casting with derivates
I'm trying to cast from one generic to another, say: myClass<MoreAbstract> anItem = myclass<DerivateFromMoreAbstract> anotherObject; Or do something like aFunction(anotherObject); // myclass<DerivateFromMoreAbstract> anotherObject where aFunction signature is aFunction(myClass<MoreAbstract> item); In fact, myClass is actually a simplified implementation of shared_ptr I found online. I'm wondering if there's any way I can actually switch from one pointer type to another being encapsulated. Is there any way to do such casting? If so, what would be the correct way to do it? If it helps anyone, VC++ gives me this error: Error 1 error C2440: 'type cast' : cannot convert from 'myClass<T>' to 'myClass<T>'
You can't static cast, as they are incompatible types. You can sometimes create an operator to coerce the type instead #include <iostream> class A { }; class B : public A { }; template<typename T> struct holder { T* value; holder ( T*value ) : value ( value ) { } template < typename U > // class T : public U operator holder<U> () const { return holder<U>( value ); } }; int main () { using namespace std; B b; holder<B> hb ( &b ); holder<A> ha = hb; cout << boolalpha; cout << ( hb.value == ha.value ) << endl; return 0; } Whether this is a meaningful operation rather depends on the semantic of the template class - if the aFunction can put anything into the handler, you don't want the more specific object being mutated. Hence you copy somehow, either with a coercion operator or with a template copy constructor and assignment. ( the coercion is less code but might result in more objects being created if you don't use reference parameters )
1,500,689
1,500,741
dynamic linking woes using c++
main.cpp <- line 106 to 164 invoke dlopen/dlsym/dlclose basefilter.hpp <- naked abstract base class basefilter.cpp examplefilter.hpp <- a test plugin examplefilter.cpp everything <- the repository Running the whole thing will result in the following error: Cannot open library "./libexamplefilter.so" ./libexamplefilter.so: undefined symbol: _ZTI10BaseFilter Since the code is pretty small and understandable you should be able to understand it right away. Anyone a clue what is wrong? Should I make rather declare create() as extern "C" void* create(void); and cast the void pointer afterwards instead of directly trying to link c++ symbols? Next Step after using -Wl,-export-dynamic, it tells me: Cannot load library symbols "./libexamplefilter.so" ./libexamplefilter.so: undefined symbol: create Uh, do I have to give a mangled c++-name there instead of "dlsym(handle, "create")". Probably. Is there a elegant way to do this? The answer is declaring create() extern "C" ... create .... This works perfectly well. Problem solved. Thanks for your help and patience.
You need to use the linker option "export-dynamic" when compiling your main executable. Normally, the main executable won't export its symbols for use by the dynamic linker (unless the symbol is used by some shared library participating in the link), which means that if your library calls back into the main exe, it will fail to load. This happens implicitly when you try to subclass a class with virtual methods and in some other cases. If you try to do this, it's a fail. So when linking your main program, add -Wl,-export-dynamic, it'll just work.
1,500,715
1,500,854
Gnu Makefile - Handling dependencies
What approach do C++ programmers on Unix platform use to create and manage Makefiles? I was using hand made Makefiles for my projects but they don't handle header file changes and other dependencies. I googled around and found a good solution here. But I ran into a problem here in the sed command - sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \ -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P; \ The problem is with the 3rd expression "-e 's/ *\$$//'. It doesn't work. Its supposed to remove trailing backslashes. I understand that there has to be double dollar there since this is part of a Makefile. Can someone tell me what wrong here? Here's the complete Makefile - CC=g++ CFLAGS=-g -Wall LIBS=-lpthread OBJS=file1.o file2.o TARGET=testProg $(TARGET) : $(OBJS) $(CC) -o $@ $^ $(CFLAGS) $(LIBS) %.o : %.cpp $(CC) -MMD -c -o $@ $< $(CFLAGS) @cp $*.d $*.P; \ sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \ -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P; \ rm -f $*.d -include $(OBJS:%.o=%.P) clean : rm -f $(TARGET) $(OBJS) all : $(TARGET) Apart from the solution to this problem, I would also like some tips/pointers to my 1st question.
I use that approach too and can't praise it highly enough. And I write my makefiles by hand and reuse them a lot on new projects. .The expression "s/ *\\$//" will work outside the context of Make. Within a makefile it doesn't work because Make tries to interpret "$/" before handing the result to the shell. So you must use "s/ *\\$$//" (note the extra $) within the makefile, but this won't work outside the context of Make (so testing it is a slight pain). EDIT: I've tried your makefile, and that sed statement seems to remove trailing backslashes just fine. Try something simpler, like this: backslash: @echo " \\" > $@ test: backslash @echo without sed: @cat backslash @echo with sed: @sed -e 's/ *\\$$//' &lt backslash EDIT: All right, now I'm hooked. Could you try these experiments and tell us the results? Change the last character to 'z' : s/.$/z/ Change a trailing backslash to 'z' : s/\\$/z/ Change a trailing backslash to 'z' : sm\\$mzm Delete a trailing backslash : s/\\$// Delete spaces and a trailing backslash: s/ *\\$// Try all of these inside and outside of Make, with '$' and '$$'.
1,501,085
1,501,166
Duplicating base-class constructors to subclass?
I have a large set classes which I need to "wrap" in a very thin subclass. The functionality of the base classes doesn't change, and their interface remains intact. The problem is, that in order to use the base classes's constructors (and most of them have more than one), I need to decalre an identical constructor in each of the subclasses, and simply pass the parameters over to the constructor of the base class (99% of the time I have nothing else to do upon construction). That's a lot of pointless work. What's the easiest way to do this? Edit: Even if it's not natively supported in the language, maybe there's some tool that can auto-generate that code?
You could add templated constructors for all possible parameters to your wrapper class: template<class Base> class wrapper : public Base { public: wrapper() : Base() {} template<typename T1> wrapper(T1 a1) : Base(a1) {} template<typename T1, typename T2> wrapper(T1 a1, T2 a2) : Base(a1, a2) {} // ... }; Since the templates will not be instantiated for constructors that aren't called it doesn't matter if these other constructors would be invalid. Only the constructors that are actually used need to exist in the base class: class A { public: A(int a) {}; }; int main() { wrapper<A> aw(1); return 0; } Probably there are some corner cases where this approach will lead to problems, but for simple cases it works.
1,501,111
1,501,297
Boost equivalent of ManualResetEvent?
I'm wondering if there is a boost equivalent of ManualResetEvent? Basically, I'd like a cross-platform implementation... Or, could someone help me mimic ManualResetEvent's functionality using Boost::thread? Thanks guys
It's pretty easy to write a manual reset event when you have mutexes and condition variables. What you will need is a field that represents whether your reset event is signalled or not. Access to the field will need to be guarded by a mutex - this includes both setting/resetting your event as well as checking to see if it is signaled. When you are waiting on your event, if it is currently not signaled, you will want to wait on a condition variable until it is signaled. Finally, in your code that sets the event, you will want to notify the condition variable to wake up anyone waiting on your event. class manual_reset_event { public: manual_reset_event(bool signaled = false) : signaled_(signaled) { } void set() { { boost::lock_guard<boost::mutex> lock(m_); signaled_ = true; } // Notify all because until the event is manually // reset, all waiters should be able to see event signalling cv_.notify_all(); } void unset() { boost::lock_guard<boost::mutex> lock(m_); signaled_ = false; } void wait() { boost::lock_guard<boost::mutex> lock(m_); while (!signaled_) { cv_.wait(lock); } } private: boost::mutex m_; boost::condition_variable cv_; bool signaled_; };
1,501,292
1,501,299
How do you decipher complex declarations of pointers+arrays?
Although I use std::vector almost all the time, I am interested in understanding as much as I can about pointers. Examples of what I am talking about: char* array[5]; // What does it mean? // 1) pointer to an array of 5 elements! // 2) an array of 5 pointers? I am interested in the precise definition of this declaration.
Not just pointers and arrays: How to interpret complex C/C++ declarations: Start reading the declaration from the innermost parentheses, go right, and then go left. When you encounter parentheses, the direction should be reversed. Once everything in the parentheses has been parsed, jump out of it. Continue till the whole declaration has been parsed. One small change to the right-left rule: When you start reading the declaration for the first time, you have to start from the identifier, and not the innermost parentheses. You example: char* array[5]; Is an array of 5 pointers to char.
1,501,338
1,501,458
What advantages can I get from learning C++ if I'm mainly a C# Programmer?
Recently I've started to notice a lot of smirks and generally rude comments whenever I mention C#. Everyone I talk to either says learn Python or learn C++. Python is a nice language, I get it. But I don't find much use for it right now (for my use cases), and C++ I heard is a faster language (not sure). So my question is this, what advantage can I get from learning C++ (besides the knowledge and expansion of my horizons), when I mainly program in C#?
I have been C++ developers for last 10 years and last two years, I have been using java for new product development. I have also done some programming on C# just to learn it. Based on my experience I would say C++ is a challenging and high performance language which is good for computer science students to understand programming concept and algorithms. Other usage of C++ would be protocol implementation which doesn't change often E.g implementing SIP Proxy or HTTP Server.. For practice product development where requirements changes often, I would recommend any high level language where developers can focus on application logic instead of reinventing wheel. E.g Recently I started an open source project xcapserver which I was able to do quick prototype in two days using java technologies (Glassfish,REST, log4j, eXist db)but I wanted to lean boost libraries and again it's a protocol which is not expected to change often, so I decided to implement in C++. I spent 4 days just to get the logger working using BOOST::log and another 4 days to fix the thread deadlock issues with Berkeley DB XML. Another aspect is product maintenance. I have spent days and night to fix memory leaks and corruption and learning curve for new developers is too high versus J2EE or .NET where it's easy to find developers and maintenance is much easier. In sort, C++ is good programming language which I would recommend to all developers to learn but I don't see much use of it going forward as processors are becoming faster and cheaper so performance is not the reason.
1,501,341
1,501,367
Reference type and pointer in disassembly
Why reference types and pointers are same in compiled code?(You can see in third and fourth line). I tried to figure it out but apparently I could not achieve. If a reference type variable must be initialized at declaration and can not be changed so is there any need to do indirection as in pointers? int x = 10; mov dword ptr [x],0Ah int y = x; mov eax,dword ptr [x] mov dword ptr [y],eax int &i = y; lea eax,[y] mov dword ptr [i],eax int *p = &x; lea eax,[x] mov dword ptr [p],eax p = &i; mov eax,dword ptr [i] mov dword ptr [p],eax x = i; mov eax,dword ptr [i] mov ecx,dword ptr [eax] mov dword ptr [x],ecx
If the referece is known by the compiler to always refer to a single particular object/item, then the compiler could certainly optimize away the indirection. However, most references are in fact bound at runtime. Even if a particular instance of a reference can't be rebound, different executions of a particular scope or different instances of an object that contains reference members may run with the reference bound to a different object for each of those instances. Using indirection is a conventient way for the compiler to deal with this. The situation where a reference is only ever bound to a single thing might be relatively infrequent enough that compilers might not look for the optimization - especially since it may be that the optimization wouldn't be a noticable gain in most cases. Also, I suspect you're not turning on compiler optimizations - using your code and calling various functions with y and i and their addresses, a quick test in VC++ 2005 with optimizations on shows that the compiler is not implementing i as a pointer, but as a true alias for y (ie., whenever passing i or &i, the compiler uses the address of y directly). If you're looking at the debug output of a compiler, it shouldn't surprise you that it always treats a reference as a pointer behind the scenes.
1,501,446
1,501,830
Will splitting code into several .cpps decrease compilation time?
Suppose a have a fairly complex class I'm working on. Half the methods are done and tested, but I'm still devolping the other half. If I put the finished code in one cpp and the rest in another, will Visual Studio (or any other IDE for that matter) compile faster when I only change code that's in the "work-in-progress" cpp? Thanks!
It really depends. For a very large project, link time can often be considerably more expensive than the time to compile a single file. In our codebase at work (a game based on the Unreal Engine) we actually found that making "bulk.cpp" files that include many other files (effectively fewer translation units) decreases the turn around time significantly. Even though individual compile time for a small change was increased, overall compile time (full rebuild) and link time (which happens even for a small change) both decreased dramatically.
1,501,510
1,501,569
Linked list and copy constructor
I'm trying to write a basic, singly-linked list class in C++. I did it in my data structures class years back, but I can't remember the details. Should my Node class have a copy constructor? It has a Node* as a member variable, and as far as I know you're always supposed to write a copy constructor, destructor, and assignment operator for classes that have dynamic members. But from what I've seen on the net, the List class takes care of the copying of Nodes. Is this really the case, and if so, why?
You could do worse than copy the design of sgi's slist -- sgi's template library ("stl") was the basis for the part of the C++ standard library that's often still (not technically correctly;-) referred to as "stl". Unfortunately slist didn't make it (its doubly-linked cousin list OTOH did make it, and became std::list) but I do like it. If you don't want to template the payload type and the allocator, it's fine to hard-code them, I guess; but the key point to retain is that "nodes" are an internal implementation detail -- you only expose the container type, with all the nice, canonical aspects (and of course the payload type must be known -- it's not hard to template it, btw;-), and you make "node" an opaque class in your .h (which just contains a class node;, and pointers to it in your class slist).
1,501,516
1,501,579
OpenGL / C++ - How do you fill an area surrounding a point on a mouse click?
I've got the mouseclick handler correctly set up. I have a drawing with some shapes. Is there any way for me to fill the surrounding part of a point until it hits a polygon boundary. Something like Microsoft Paint's "fill" command. Thanks!
Consider using OpenGL selection capabilities with glSelectBuffer. Refer to this chapter of the red book for explanation.
1,501,768
1,501,789
'variable name' cannot appear in a constant expression c++
Anyone have any clue what this error might actually mean? I'm tripping on a bit of code that can't seem to get around it. I've tried it with just h*2 instead of hprime, and just w*2 instead of wprime. Every time I get the same compiler (g++ compiler) error of : grid.cpp: In constructor ‘Grid::Grid(int, int)’: grid.cpp:34: error: ‘hprime’ cannot appear in a constant-expression (the compiler doesn't always say hprime, it will say whatever variable is there, be it h or hprime or width). Any help would be greatly appreciated! class Grid { public: Grid(int x, int y); ~Grid(); void addObstacle(int w, int h); void toString(); int** grid; int height; int width; }; Grid::Grid(int w, int h) { width = w; height = h; const int hprime = h*2; const int wprime = w*2; grid = new int[wprime][hprime]; for(int x=0;x<wprime;x++) { for (int y=0; y<hprime;y++) { grid[x][y] = 0;<br> } } }
You can't use new to allocate a two-dimensional array, but you can change the offending line like this: grid = new int*[wprime]; for (int i = 0 ; i < wprime ; i++) grid[i] = new int[hprime]; If it doesn't have to be multidimensional, you can do: grid = new int[wprime*hprime]; and just index it like grid[A*wprime + B] where you would normally index it like grid[A][B]
1,501,803
1,502,065
Convert AES encrypted string to hex in C++
I have a char* string that I have encoded using AES encryption. This string contains a wide range of hex characters, not just those viewable by ASCII. I need to convert this string so I can send it through HTTP, which does not accept all of the characters generated by the encryption algorithm. What is the best way to convert this string? I have used the following function but there are a lot of blanks (0xFF), it cant convert all of the characters. char *strToHex(char *str){ char *buffer = new char[(dStrlen(str)*2)+1]; char *pbuffer = buffer; int len = strlen( str ); for(int i = 0; i < len ; ++i ){ sprintf(pbuffer, "%02X", str[i]); pbuffer += 2; } return buffer; } Thank you, Justin
A few problems. First, your characters are probably signed, which is why you get lots of FF's - if your character was 0x99, then it gets sign extended to 0xFFFFFF99 when printed. Second, strlen (or dStrlen - what is that?) is bad because your input string may have nulls in it. You need to pass around the string length explicitly. char *strToHex(unsigned char *str, int len){ char *buffer = new char[len*2+1]; char *pbuffer = buffer; for(int i = 0; i < len ; ++i ){ sprintf(pbuffer, "%02X", str[i]); pbuffer += 2; } return buffer; }
1,501,859
1,501,862
Why Size of Class with a member function is 1 byte..While member function is 4 bytes
I am not getting Why Size of Class with a member function is 1 byte..While member function is 4 bytes in the following example. class Test { public: Test11() { int m = 0; }; }; int main() { Test t1; int J = sizeof(t1); int K = sizeof(t1.Test11()); return 0; } Here J becomes 1 Byte and K becomes 4 bytes. If K=4, then why size of class is not 4 bytes instead it shows 1 Byte
The function itself is not actually stored in the class. Only the class's data members (and possibly its vtable pointer, if it has one) affect its size. The function itself lives in the executable code region, and all instances of the same type of class use that one definition of the function. The compiler does not actually copy out the entirety of a function body every time you create a new instance of the class. Also, sizeof(t1.Test11()) does not mean "the size of the function Test::Test11's executable code in bytes." It means "the size of the type returned by Test::Test11".
1,501,920
1,501,970
Base Copy constructor not called
class Base { public: int i; Base() { cout<<"Base Constructor"<<endl; } Base (Base& b) { cout<<"Base Copy Constructor"<<endl; i = b.i; } ~Base() { cout<<"Base Destructor"<<endl; } void val() { cout<<"i: "<< i<<endl; } }; class Derived: public Base { public: int i; Derived() { Base::i = 5; cout<<"Derived Constructor"<<endl; } /*Derived (Derived& d) { cout<<"Derived copy Constructor"<<endl; i = d.i; }*/ ~Derived() { cout<<"Derived Destructor"<<endl; } void val() { cout<<"i: "<< i<<endl; Base::val(); } }; If i do Derived d1; Derived d2 = d1; The copy constructor of base is called and default copy constructor of derived is called. But if i remove the comments from derived's copy constructor the base copy constructor is not called. Is there any specific reason for this? Thanks in advance.
If you want to read actual rule you should refer to C++ Standard 12.8/8: The implicitly-defined copy constructor for class X performs a memberwise copy of its subobjects. The order of copying is the same as the order of initialization of bases and members in a user-defined construc- tor (see 12.6.2). Each subobject is copied in the manner appropriate to its type: if the subobject is of class type, the copy constructor for the class is used; if the subobject is an array, each element is copied, in the manner appropriate to the element type; if the subobject is of scalar type, the built-in assignment operator is used. When you define copy constructor explicitly you should call copy c-tor of base class explicitly.
1,502,244
1,502,268
How can I use C++ code to interact with PHP?
I was reading somewhere that sometimes PHP is simply not fast enough and that compiled code has to sometimes "do the heavy lifting" What is the api in C++ to do this?
You can add functions/classes to PHP, programmed in C (and you can wrap a C++ class from C, if I remember correctly from an article I read some time ago), which might allow you to do some things faster -- if programmed well : no need for interpretation of PHP code ; only execution of machine code, which is generally way faster. To do that, you'll have to develop a PHP extension. There are not that many resources available on the Internet about that, but these one might help you to start : Extension Writing Part I: Introduction to PHP and Zend Extension Writing Part II: Parameters, Arrays, and ZVALs Extension Writing Part III: Resources And, specifically about the C++ part, this one might help too : Wrapping C++ Classes in a PHP Extension If you are really interested by the subject, and ready to spend some money on it, you could also buy the book Extending and Embedding PHP (some pages are available as preview on Google Books too) ; I've seen a couple of times that it was the book to read when interested on this subject (In fact, I've bought it some time ago, and it's an interesting read) By the way, the author of that book is also the author of the first four articles I linked to ;-)
1,502,629
1,502,641
Function declarations and an unresolved external
I am looking after a huge old C program and converting it to C++ (which I'm new to). There are a great many complicated preprocessor hacks going on connected to the fact that the program must run on many different platforms in many different configurations. In one file (call it file1.c) I am calling functionA(). And in another file (call it file2.c) I have a definition of functionA(). Unfortunately the exact type of the function is specified by a collection of macros created in a bewildering number of ways. Now the linker is complaining that: functionA is an unresolved external symbol. I suspect that the problem is that the prototype as seen in file1.c is slightly different from the true definition of the function as seen in file2.c. There is a lot of scope for subtle differences due to mismatches between _cdecl and fastcall, and between with and without __forceinline. Is there some way to show exactly what the compiler thinks is the type of functionA() as seen by file1.c as opposed to file2.c?
You can pass a flag to the compiler (/P, I think) that causes it to output the complete preprocessed output that is passed to the compiler - you can then open this (huge) file, and search through it and the information you need will be in there, somewhere.
1,502,677
1,521,826
WinHTTP IWinHttpRequest iface - cookie handling - how to get cookies from response?
I'm using WinHTTP IWinHttpRequest object. I do POST to a https domain specyfying a request body with credentials. The site is expected to return cookies in HTTP response. The code works in Wininet - but I don't know how in WinHTTP to get cookies from the HTTP response? Can anybody help? Dominik
I would start with the Cookie Handling in WinHTTP article on MSDN. If you want to do things manually, here's an (ugly) VB code sample you can crib from: http://www.devnewsgroups.net/group/microsoft.public.exchange.development/topic58495.aspx)
1,502,791
1,502,912
Why check only certain values for errors? (C++?)
I recently started learning DirectX/Windows, and the book I'm learning from had the code d3d = Direct3DCreate9(D3D_SDK_VERSION); if(d3d == NULL) //catch error &c. My question is: What would cause an error in this line, that is different than what would cause an error in another line (say, for example, int num = 42)?
d3d = Direct3DCreate9(D3D_SDK_VERSION); if (d3d == NULL) This is an error or not according to the meaning you give to the return value of Direct3DCreate9, i.e. depending on the specification of the function. I've written many pointer-returning functions for which NULL as a return value was not an erroneous situation. So, do not equate "a function returning NULL" to "an error". An unambiguous error is a crash (technically, undefined behaviour) in your code, like if d3d is indeed NULL and later you dereference it. int num = 42; Here you are declaring an int variable called num and initializing it with a value of 42. What kind of error can you think of? Obviously, num will never "be NULL", if that bothers you. 42 may be a correct value or an error, depending on the context.
1,502,888
1,502,894
C# - Executables decompilable (can be reverse engineered)?
Is that right that C# can be reverse engineered? How is easy to do that? Can we say the C# is not enough good from safety aspect? And what about C++ compared with C# against decompiling?
It's true! Take a look at one of your own executables using Reflector. Does this mean that C# is "not enough good from safety aspect"? No, it doesn't mean that. There's nothing wrong with the safety of C#. You just need to ensure that you don't put any secrets in your published executables if you don't want the world to know about them. (This applies to pretty much any language, not just C#. All executable code can be reverse-engineered, it's just that some languages/frameworks make it easier than others.)
1,503,006
1,503,023
unresolved external mystery
My linker is reporting an error as follows: unresolved external symbol "unsigned char __fastcall BD_CLC(int,int)"... But I maintain that all references to this function, as well as the definition of the function are of the form: __forceinline UBYTE BD_CLC(int swap,int elem); I even did a compilation with "Generate preprocessed file" set and went through the output. In every file where BD_CLC was used, the function was declared as __forceinline UBYTE BD_CLC(int swap,int elem); and of course the actual function definition was declared as __forceinline UBYTE BD_CLC(int swap,int elem) { ... } Any ideas?
Since you've declared the function __forceinline, you need to make sure the definition - not just the declaration - is visible everywhere the function is called.
1,503,266
1,524,755
How do I change the lookup path for .NET libraries referenced via #using in Managed C++?
I developed a DLL in Managed C++ which loads some plugins (implemented in any .NET language) at runtime using System.Reflection.Assembly.LoadFile. The interface which is implemented by all plugins is implemented in C#. It's used by the Managed C++ code like this: #using <IMyPluginInterface.dll> // Make the 'IMyPluginInterface' type available ref class PluginManager { List<IMyPluginInterface ^> ^m_plugins; // Load all plugins in a well-known directory. void load() { for ( string dllFile in Directory.GetFiles( .., "*.dll" ) ) { // Lookup the type of the plugin object using Reflection Type pluginType = ...; // Finally, instantiate the plugin and add it to our list. m_plugins.Add( (IMyPluginInterface ^)Activator.CreateInstance( pluginType ) ); } } } Loading the plugins works well; the problem I'm facing is that at runtime, the IMyPlugnInterface.dll file might not be in the same directory as the Managed C++ DLL. This means that the 'IMyPluginInterface' type is not available at runtime, and an exception is thrown. I previously asked whether it was maybe possible to influence the lookup path used when resolving DLLs referenced via the #using statement. Unfortunately, this didn't yield any result. Is there maybe a different approach to this? Can types which are referenced via #using be compiled into the Managed C++ DLL? Maybe anybody else has an entirely different solution?
You can use several options - if you know in advance where the assembly will be located, you can add that path to your application's configuration file: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="MyPath"/> </assemblyBinding> </runtime> </configuration> If you want to search for the assembly at runtime, you can implement a handler for AppDomain::CurrentDomain->AssemblyResolve event: ref class AssemblyResolver { public: /// The path where the assemblies are searched property String^ Path { String^ get() { return path_; } } explicit AssemblyResolver(String^ path) : path_(path) { /* Void */ } Assembly^ ResolveHandler(Object^ sender, ResolveEventArgs^ args) { // The name passed here contains other information as well String^ dll_name = args->Name->Substring(0, args->Name->IndexOf(',')); String^ path = System::IO::Path::Combine(path_, dll_name+".dll"); if ( File::Exists(path) ) return Assembly::LoadFile(path); return nullptr; } private: String^ path_; }; and you can wire it using something like this: AssemblyResolver^ resolver = gcnew AssemblyResolver(path); AppDomain::CurrentDomain->AssemblyResolve += gcnew ResolveEventHandler( resolver, &AssemblyResolver::ResolveHandler ); Just make sure this is done before calling any methods that may use types from the assembly that has to be resolved.
1,503,504
1,503,538
Using all overloads of the base class
When a subclass overrides a baseclass's method, all of the baseclass's overloads are not available from the subclass. In order to use them there should be added a using BaseClass::Method; line in the subclass. Is there a quick way to inheirt the baseclass's overloads for ALL of the overridden methods? (not needing to explicitly specify using ... for each method)
No. It's only possible with a using declaration and that only works with the individual methods.
1,503,542
1,503,560
Variable-sized bitfields with aliasing
I have some struct containig a bitfield, which may vary in size. Example: struct BitfieldSmallBase { uint8_t a:2; uint8_t b:3; .... } struct BitfieldLargeBase { uint8_t a:4; uint8_t b:5; .... } and a union to access all bits at once: template<typename T> union Bitfield { T bits; uint8_t all; // <------------- Here is the problem bool operator & (Bitfield<T> x) const { return !!(all & x.all); } Bitfield<T> operator + (Bitfield<T> x) const { Bitfield<T> temp; temp.all = all + x.all; //works, because I can assume no overflow will happen return temp; } .... } typedef Bitfield<BitfieldSmallBase> BitfieldSmall; typedef Bitfield<BitfieldLargeBase> BitfieldLarge; The problem is: For some bitfield base classes, an uint8_t is not sufficient. BitfieldSmall does fit into a uint8_t, but BitfieldLarge does not. The data needs to be packed as tightly as possible (it will be handled by SSE instructions later), so always using uint16_t is out of question. Is there a way to declare the "all" field with an integral type, whose size is the same as the bitfield? Or another way to access bits as a whole? I can of course forego the use of the template and declare every kind of bitfield explicitly, but I would like to avoid code repetition (there is quite a list of operators und member functions).
You could make the integral type a template parameter as well. template<typename T, typename U> union Bitfield { T bits; U all; } typedef Bitfield<BitfieldSmallBase, uint8_t> BitfieldSmall; typedef Bitfield<BitfieldLargeBase, uint16_t> BitfieldLarge;
1,503,716
1,504,679
Video in Qt S60 application?
Has anyone built a Qt S60 app (3rd edition, FP2) that plays (streaming or local) video? I want to play video 'in' a widget, not with (say) QDesktopServices. I know there's documentation about how to do this with Symbian, such as here and here but I'm still stuck. (Apologies in advance for cross-posting: I've asked elsewhere, but with no success.)
Qt 4 includes a suite of multimedia APIs called Phonon, which allow you to do just this. They are currently being implemented for Symbian - while the Qt for S60 "Tower" pre-release does not include support for Phonon on Symbian, Qt 4.6 will do. In the meantime, your only option is to use the Symbian MMF APIs directly. Specifically, your video widget - or an object owned by it - will need to create an instance of CVideoPlayerUtility, and therefore will need to implement MVideoPlayerUtilityObserver. The video player API requires the client to provide an RWindow in which to display the video - this can be obtained by calling QWidget::winId(), which returns a CCoeControl* pointer. You can therefore obtain a window handle by calling RWindow& window = *static_cast<RWindow*>(widget->winId()->DrawableWindow()) All in all however, playing video from a Qt app (or indeed any app) on Symbian currently requires quite a lot of work - especially if you want to support dynamic re-sizing and/or re-positioning of the video content. Note also that the way in which Qt is currently implemented on Symbian means that moving other widgets (partially or completely) on top of the video widget will not work correctly - the video will continue to appear on top. This is due to the fact that calling QWidget::winId() currently doesn't cause Qt to create a native Symbian window, and will be rectified in 4.6. In summary, unless you are in a hurry to do this, it is probably better to wait for the 4.6 beta which is due in a few weeks time.
1,503,764
1,513,060
The simplest code hacking
I have the following code: #include <iostream> #include <string> void main() { std::string str; std::cin>>str; if(str == "TheCorrectSerialNumber") std::cout<<"Hello world!!!"<<std::endl; } I need a decompilation or disassemblering tool which can help me by doing below listed steps find the "TheCorrectSerialNumber". So the steps are: decompile or diassembler the executable of my code run the exe and type not the Correct Serial but something like “AAA” find my “AAA” with what string is being compared and finally find out the "TheCorrectSerialNumber". Please provide me also with directions how your suggested tool is doing above listed steps. Thanks a lot!!! NOTE: For those who tend to think that I want to crack someone’s code! First look ant my questions that I've asked just before and just after this question. I am a programmer and I need to concern about my codes security. Thus I have decided to crack my codes and to do some exercises on the other codes (on the sites that teach cracking there are a bunch of softs that are designed to be cracked) to understand how to deliver a secure code. If you know how people do cracking you probably will create more secure code that someone who doesn't know. And if you what to study how to crack you have to try. That is my point!
It is very easy to do with disassembling. You need HIEW and W32DASM tools or OllyDbg (for example). Just look at some examples of using this tools in youtube (cracking). www.wasm.ru www.cracklab.ru Very helpful sites!!!!
1,503,770
1,503,935
Best method for requeing functions
We have a windows service in C++/ MFC which has to carry out a number of tasks on the host workstation some of which may be long running and may fail a few times before they are completed. Each task will only need to be completed once and sequentially. I was of thinking of some form of callback initially to retry the failed task but each function has totally different parameters and the code has already been written and tested and just needs a re-queuing method. I thought we could write the failed task to the registry, sleep() for a while and then restart the service. Is there a better approach? TIA..
I'm doing quite the same thing in my professional project. My server component is getting runnable objects from different sources and execute them sequentially in a separated thread. All my runnable objects are using different parameters but they all have one function run(void* pUserParam). the void* parameters is a special object that contains a collection of field with different type (double, string, etc...). My component is queuing the runnable object and launch a new one each time the thread is freed. Of course my component is sleeping when queue is empty and wake up when an object arrives. In your case when a task fail you just need to re-queue it and it will automatically retry the task later. To achieve these you need: a Pool mechanism that manage a queue of tasks, a task object that contains all information about the runnable object to launch and the parameters, a runnable object that contains your action to execute. How it works: Your service is listening for demands, When a demand arrives, it give it to the Pool mechanism, The Pool take the runnable object and its parameter(s) and create a task. This task is queued, (2b. If the queue was empty, the pool wakes up the execution thread,) The Thread pick up one task from the queue and execute it calling the Run() function of the runnable object and passing to it the parameters previously stored in the task, (3b. If the task failed, the thread re-queue a task with the runnable object and its parameter(s),) The thread picks up a new task or sleeps if queue is empty. This is my approach and I know this works fine. I know with this method you need to rewrite a part of your application but then the only thing to modify when adding a sort of task is to create a new runnable object (one sort of task => one runnable object that inherit from the abstract one). Hope this will help you
1,503,839
1,504,135
How to turn off pc via windows API?
I never programmed a winapi so i have a little problem here . I need turn off my pc from my application . I found this example link text then i found this example how to change privileges link text But i have problem how to get that parameter HANDLE hToken // access token handle I think i need to make it in the next order to get the parameter OpenProcessToken LookupPrivilegeValue AdjustTokenPrivileges but there are a lot parameters that i have no idea what to do with them . maybe you have jere some example how i get that HANDLE hToken parameter to make that work . By the way I already saw the following post link text Thanks a lot all you .
This is a bit much for the comments on Daniel's answer, so I'll put it here. It looks like your main issue at this point is that your process isn't running with the priveleges required to perform a system shutdown. The docs for ExitWindowsEx contain this line: To shut down or restart the system, the calling process must use the AdjustTokenPrivileges function to enable the SE_SHUTDOWN_NAME privilege. For more information, see Running with Special Privileges. They also have some example code. In a pinch, you can just copy that.
1,503,965
1,504,005
_beginthread in XPCOM Component error C2440
I want to start thread in XPCOM Component. Here is a code for creating thread nsresult rv = NS_OK; nsCOMPtr<Callback> obj = do_CreateInstance("@jscallback.p2psearch.com/f2f;1", &rv); NS_ENSURE_SUCCESS(rv, rv); char* str="Hello from C++"; _beginthread( (void(*)(nsCOMPtr<Callback> ))&P2P::test, 0,obj); return NS_OK;//obj->Status(str); Here is a function #include "winsock2.h" #include <process.h> #include "nsCOMPtr.h" #include "Callback.h" class P2P{ public: void test(nsCOMPtr<Callback> obj){ } }; I am getting error as error C2440: 'type cast' : cannot convert from 'void (__thiscall P2P::* )(nsCOMPtr)' to 'void (__cdecl *)(nsCOMPtr)'
Make P2P::test static and add __cdecl calling convention.
1,504,205
1,504,252
How can I implement a 'main' method in a class in C++?
Consider: static class EntranceClass { public: static void RegisterSomething() { } static int main() { RegisterSomething(); return 0; } } // <-- Expected unqualified-id at the end I'm getting the following error: expected unqualified-id at end of input main.cpp Problem Is there a solution?
The error is referring to the use of the static keyword before the class definition - the compiler expects a variable name after that (as in C++ there is no such thing as a static class). And if you want to use static int EntranceMain::main(void) as your program's entry point, then one way to do it is to tell that to your linker, i.e., give it a full, decorated name of that function. This is highly dependent on which compiler and linker you use, so you need to refer to their documentation. But using that will probably mean you need to include the startup code (e.g., CRT initialisation). Note that this is not so standard-compliant, though.
1,504,251
1,504,307
Heap corruption: What could the cause be?
I am investigating a crash due to heap corruption. As this issue is non-trivial and involves analyzing the stack and dump results, I have decided to do a code review of files related to the crash. To be frank, I don't have in-depth knowledge of when the heap could be corrupted. I would appreciate if you could suggest scenarios which could lead to heap corruption. Platform: Windows XP Language: C++ Compiler: VC6
Common scenarios include: Writing outside the allocated space of an array (char *stuff = new char[10]; stuff[10] = 3;) Casting to the wrong type Uninitialized pointers Typo error for -> and . Typo error when using * and & (or multiple of either) [EDIT] From the comments, a few more: Mixing new [] and new with delete [] and delete Missing or incorrect copy-constructors Pointer pointing to garbage Calling delete multiple times on the same data Polymorphic baseclasses without virtual destructors
1,504,323
1,505,009
Avoid reusing of the same fd number in a multithread socket application
I have an asynchronous application executing several threads doing operations over sockets where operations are scheduled and then executed asynchronously. I'm trying to avoid a situation when once scheduled a read operation over a socket, the socket gets closed and reopened(by possibly another peer in another operation), before the first operation started execution, which will end up reading the proper file descriptor but the wrong peer. The problem comes because (accept();close();accept()) returns the same fd in both accepts() which can lead to the above situation. I can't see a way of avoiding it. any hint?
Ok, found the answer. The best way here is to call accept() and get the lowest fd available, duplicate it with a number known by you like dup2(6,1000) and close(6), you have now control of the fd range you use. Next accept will come again with 6 or similar, and we'll dup2(6,999); and keep decreasing like that and reseting it if it gets too low. Since the accepting is done always in the same thread and dup2 and close aren't expensive compared to accept which is always done there it's perfect for my needs.
1,504,420
1,504,438
C++ What does the percentage sign mean?
I got this c++ macro and wonder what they mean by code%2 (the percentage sign) ? #define SHUFFLE_STATEMENT_2(code, A, B) switch (code%2) { case 0 : A; B; break; case 1 : B; A; break; }
It is for taking a modulus. Basically, it is an integer representation of the remainder. So, if you divide by 2 you will have either 0 or 1 as a remainder. This is a nice way to loop through numbers and if you want the even rows to be one color and the odd rows to be another, modulus 2 works well for an arbitrary number of rows.
1,504,464
1,522,666
Windows socket WSACleanup C++
I am using sockets on my program. Due to I added the WSAStartup. My application runs fine (It is always up till it gets a signal to stop). After getting the signal it stops te problem that if I write the WSACleanup function at the end of my program it crashes and if I remove it it terminates fine. Thanks
Couldn't resovle and find the problem.The application is using more than just sockets. Although Microsoft reference sais that onevery WSAStartup you must use WSACleanup, well this is not true and the system is releasing things regards that.
1,504,752
1,504,782
C++ Output evaluation order with embedded function calls
I'm a TA for an intro C++ class. The following question was asked on a test last week: What is the output from the following program: int myFunc(int &x) { int temp = x * x * x; x += 1; return temp; } int main() { int x = 2; cout << myFunc(x) << endl << myFunc(x) << endl << myFunc(x) << endl; } The answer, to me and all my colleagues, is obviously: 8 27 64 But now several students have pointed out that when they run this in certain environments they actually get the opposite: 64 27 8 When I run it in my linux environment using gcc I get what I would expect. Using MinGW on my Windows machine I get what they're talking about. It seems to be evaluating the last call to myFunc first, then the second call and then the first, then once it has all the results it outputs them in the normal order, starting with the first. But because the calls were made out of order the numbers are opposite. It seems to me to be a compiler optimization, choosing to evaluate the function calls in the opposite order, but I don't really know why. My question is: are my assumptions correct? Is that what's going on in the background? Or is there something totally different? Also, I don't really understand why there would be a benefit to evaluating the functions backwards and then evaluating output forward. Output would have to be forward because of the way ostream works, but it seems like evaluation of the functions should be forward as well. Thanks for your help!
The C++ standard does not define what order the subexpressions of a full expression are evaluated, except for certain operators which introduce an order (the comma operator, ternary operator, short-circuiting logical operators), and the fact that the expressions which make up the arguments/operands of a function/operator are all evaluated before the function/operator itself. GCC is not obliged to explain to you (or me) why it wants to order them as it does. It might be a performance optimisation, it might be because the compiler code came out a few lines shorter and simpler that way, it might be because one of the mingw coders personally hates you, and wants to ensure that if you make assumptions that aren't guaranteed by the standard, your code goes wrong. Welcome to the world of open standards :-) Edit to add: litb makes a point below about (un)defined behavior. The standard says that if you modify a variable multiple times in an expression, and if there exists a valid order of evaluation for that expression, such that the variable is modified multiple times without a sequence point in between, then the expression has undefined behavior. That doesn't apply here, because the variable is modified in the call to the function, and there's a sequence point at the start of any function call (even if the compiler inlines it). However, if you'd manually inlined the code: std::cout << pow(x++,3) << endl << pow(x++,3) << endl << pow(x++,3) << endl; Then that would be undefined behavior. In this code, it is valid for the compiler to evaluate all three "x++" subexpressions, then the three calls to pow, then start on the various calls to operator<<. Because this order is valid and has no sequence points separating the modification of x, the results are completely undefined. In your code snippet, only the order of execution is unspecified.
1,505,318
1,505,397
C++ implicitly calling a function When? and How?
I have a couple questions. Are all functions inside of a class member functions? or only the ones preceded by the declaration "friend"? The significance of member functions are that they cannot be accessed by any other classes correct? What is the difference between an implicit and explicit call? Which functions can or cannot be implicitly called? I was hoping to see an example of implicit and explicit calling. EDIT: Thanks for the great answers, there were lot of bits and pieces that answered my question and thanks for the links to the books. I will read them.
Are all functions inside of a class member functions? or only the ones preceded by the declaration "friend"? Friend functions are not member functions. All what they differ from regular global functions is that they can access non-public area of the class. For example: class myclass { friend void fun(const myclass& obj); int x; }; void fun(const myclass& obj) { std::cout << obj.x; // x is private member } What is the difference between an implicit and explicit call? When you call a function using the () operator, it is an explicit call. If you don't do it that way, it is an implicit one. Example of an explicit call: fun(); Examples of implicit calls: void someScope(){ myclass myobject; // constructors called } // destructor of myobject is called before exiting the function .... myclass* mySecondObject = new myclass; // constructor called delete mySecondObject; // destructor called
1,505,335
1,505,436
How do you use markers in vi?
I just discovered the existence of markers in vi. How do you use it, what do you know about them? are they useful, say for a C++ developer?
I use them all the time for: commenting out blocks of code, copying and moving blocks of code, yanking and deleting blocks of code into named buffers, and Edit: substituting in a block of test. Commenting out: go to the first line of the code you want to comment out, mark it, e.g. enter ma go to the end of the block enter :'a,.s/^/# (or whatever comment character you need) Copying and moving: mark first line as above, go to bottom of block you want to copy/move enter your second different marker, e.g. mb go to where you want to copy the block and enter :'a,'bco . or :'a,'bmo . to copy or move resp. Yanking to a named buffer: mark first line as above, go to bottom of block you want to yank enter :'a,.ya a will yank the block into buffer a or :'a,.ya A will append the block onto the current contents of buffer a Edit: Substituting in a block of text: mark first line as above, go to the bottom of the block you want to substitute in enter :'a,.s/search_string/replace_string/[gc] which will subtitute in your text block. Adding 'g' or 'c' after the last slash will invoke the usual global and confirm functionality. Edit: Forgot to say, remember that 'a (apostrophe a) refers to the line containing the marker and `a (backtick a) refers to the character on the line that you marked. So `ad`b (bactic-a-d-backtic-b) is a useful little snippet to delete the text in a line from the char marked with 'a' up to the char before the char marked with b. By the way, in Vim, entering :reg will give you the contents of all your registers incl. your delete registers.
1,505,489
1,520,632
memory leak when calling unmanaged code from managed code in Windows 7
When I call an unmanaged C++ code from my C# code, I seem to have some kind of a memory leak. The C++ reads data from a file using ifstream.read, and writes it to a Vector. This happens only after upgrading to Windows 7, doesn't happen on Vista, but if I use a version of the native dll that was compiled on Vista, it doesn't change anything! If I run the same C++ code directly, without the managed interope, there is no memory leak! If I run the managed process, but within the vshost process, there is no memory leak! Here's the call signature: [DllImport(DllPath, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.I1)] public static extern bool MyMethod( int x, string y, string z, bool v, bool w); and the native one: MyDll_Export bool APIENTRY MyMethod( int x, const wchar_t* y, const wchar_t* z, bool v, bool w) When I call it from C++, I call it like this: MyMethod(1, L"My String 1", L"My String 2", true, true) When I look at the performance counters for managed and unmanaged memory, I see that all of the memory comes from the unmanaged code. Considering that the marshaling is pretty simple, I don't understand why there is a difference between calling the C++ directly or through C#. I also don't know why would this happen only on Windows 7 (both Windows installations had .net 3.5 SP1). Does anyone have an idea what's the reason for this? Also if anyone knows of a native memory profiling tool that works on Window 7, I'd be glad to know (for now I've just printed to console all explicit memory allocation and there are no differences).
I'm sure the problem is related to marshaling the C# data types to their C++ counter parts. Since you are marshaling the return value bool to a signed 1 byte value, maybe you should do the same to the function arguments? The C# bool type is 4 bytes, maybe you are leaking there? Also, specifying the unmanaged type for the strings may help. [DllImport(DllPath, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.I1)] public static extern bool MyMethod( int x, [MarshalAs(UnmanagedType.LPWStr)] [In] string y, [MarshalAs(UnmanagedType.LPWStr)] [In] string z, [MarshalAs(UnmanagedType.I1)] bool v, [MarshalAs(UnmanagedType.I1)] bool w); An explanation for the commentor: For the C++ bool type: In general, a zero or null-pointer value is converted to false, any other value is converted to true. ... The 1998 C++ Standard Library defines a specialization of the vector template for bool. The description of the class indicates that the implementation should pack the elements so that every bool only uses one bit of memory. So, pretty much whatever value you use, you'll get a c++ boolean with the value true or false.
1,505,582
1,505,631
Determining 32 vs 64 bit in C++
I'm looking for a way to reliably determine whether C++ code is being compiled in 32 vs 64 bit. We've come up with what we think is a reasonable solution using macros, but was curious to know if people could think of cases where this might fail or if there is a better way to do this. Please note we are trying to do this in a cross-platform, multiple compiler environment. #if ((ULONG_MAX) == (UINT_MAX)) # define IS32BIT #else # define IS64BIT #endif #ifdef IS64BIT DoMy64BitOperation() #else DoMy32BitOperation() #endif Thanks.
Unfortunately there is no cross platform macro which defines 32 / 64 bit across the major compilers. I've found the most effective way to do this is the following. First I pick my own representation. I prefer ENVIRONMENT64 / ENVIRONMENT32. Then I find out what all of the major compilers use for determining if it's a 64 bit environment or not and use that to set my variables. // Check windows #if _WIN32 || _WIN64 #if _WIN64 #define ENVIRONMENT64 #else #define ENVIRONMENT32 #endif #endif // Check GCC #if __GNUC__ #if __x86_64__ || __ppc64__ #define ENVIRONMENT64 #else #define ENVIRONMENT32 #endif #endif Another easier route is to simply set these variables from the compiler command line.
1,505,675
1,505,740
power of an integer in c++
I need to get the result from pow(a,b) as an integer (both a and b are integers too). currently the calculations where (int) pow( (double)a, (double)b) is included are wrong. Maybe someone can help with a function that does the pow(a,b) with integers and returns an integer too? But here is the odd part: I made my script in Linux with Geany (and g++/gcc compiler) and had just pow(a,b) the script compiled and worked fine. But in university I have Dev-C++ (and MS Windows). In Dev-C++ the script didn't compile with an error [Warning] converting toint' from double' I need to make this scrpit work under Windows (and Mingw compiler) too.
A nice recursive approach you can show off: int myPow(int x, int p) { if (p == 0) return 1; if (p == 1) return x; return x * myPow(x, p-1); }
1,505,676
1,505,709
How do I increment an IP address represented as a string?
I have an IP address in char type Like char ip = "192.123.34.134" I want increment the last value (134). Does anyone how should i do it? I think, i should convert it to an integer, and then back, but unfortunately i don't know how? :( I'm using C++. Please help me! Thanks, kampi
You can convert the IP address from a string to an integer using inet_addr, then, after manipulating it, convert it back to a string with inet_ntoa. See the documentation for these functions for more info on how to use them. Here's a small function that will do what you want: // NOTE: only works for IPv4. Check out inet_pton/inet_ntop for IPv6 support. char* increment_address(const char* address_string) { // convert the input IP address to an integer in_addr_t address = inet_addr(address_string); // add one to the value (making sure to get the correct byte orders) address = ntohl(address); address += 1; address = htonl(address); // pack the address into the struct inet_ntoa expects struct in_addr address_struct; address_struct.s_addr = address; // convert back to a string return inet_ntoa(address_struct); } Include <arpa/inet.h> on *nix systems, or <winsock2.h> on Windows.
1,505,704
1,510,111
How to launch process with limited memory?
How does one create and launch process (i.e. launch an .exe file) with RAM limitation using c++ and the win32 API? Which error code will be returned, if the proccess goes beyond the limit?
Job Objects are the right way to go. As for an error code, there really isn't one. You create the process (with CreateProcess) and the job (with CreateJobObject), then associate the process with the job object (with AssignProcessToJobObject). The parent process won't get an error message if the child allocates more than the allowed amount of memory. In fact, the limit will be enforced even if the parent process exits. If the child process tries to allocate more than the allowed amount of memory, the allocation will simply fail.
1,506,131
1,506,160
How to debug a multithreaded application in C++ which is hung (deadlock)?
In java debugging a hung application is easy. You can take the memory dump of the application and use and use eclipse jvm dump analyser to see the status of the threads and where each threads were blocked? Does something like this exists for C++?
You can do the exact same thing with C++; force a core dump and look into it after. Or, if you're using MSVC, you can simply attach the debugger to the application while it's running. Hit "break all" and poke around through the threads.
1,506,313
1,506,339
call back member function in c++
class scanner { private: string mRootFilePath; static int AddToIndex( const char *,const struct stat *,int); public: scanner(string aRootFilePath){ mRootFilePath = aRootFilePath; } string GetFilepath(){ return mRootFilePath; } void Start(); }; int scanner :: AddToIndex(const char *fpath, const struct stat *sb,int typeflag) { fprintf(stderr,"\n%s\t%d",fpath,typeflag); return 0; } void scanner :: Start() { ftw(mRootFilePath.c_str,(int (*)( const char *,const struct stat *,int))scanner :: AddToIndex,200); } main() { int i; scanner test("."); test.Start(); } When I compile this code I get error message main.c: In member function ‘void scanner::Start()’: main.c:34: error: argument of type ‘const char* (std::basic_string<char, std::char_traits<char>, std::allocator<char> >::)()const’ does not match ‘const char*’ ftw function calls the call back function in this case AddToIndex() function which is a member function of the class "scanner".. how can make this member function AddToIndex as a call back function? And How to resolve this issue...
In your call to ftw, the first parameter is mRootFilePath.c_str. Perhaps you want mRootFilePath.c_str() instead?
1,506,456
1,506,541
Object files do not contain symbols that should be there
This is the specific error I am getting: libFoo.so: undefined reference to `IID_IFOOBAR' collect2: ld returned 1 exit status make: *** [/home/F.exe] Error 1 when I try to check the symbols in my object file A.o nm A.obj | grep IID_ I get no symbols listed in my object file of the 'IID_IFOOBAR' that should be there since it is defined in a header file as: extern const blahType IID_IFOOBAR Am I missing something? Should IID_IFOOBAR be defined differently somewhere since it is an extern variable? If this question is too specific I will remove it. But perhaps someone's intuition will help me here.
[EDIT] Add the definition of the variable somewhere (without extern). Extern identifiers without initializers are not definitions - the definition must be somewhere else.
1,506,727
1,506,773
Assigning object to method call
I have a class whose name is YourClass. And my problem is WHY compiler do NOT generate an error for following code? YourClass AMethod(){ return YourClass();} AMethod() = YourClass(); [In this case IN MY OPINION AMethod just return a value (I mean it do not have a l-value).] EDIT: If I can do that above why I can not do following int AMethod(){ return a;} AMethod() = 5;
EDIT1: I think I miss understood the question first time. The standard says: 3.10 Lvalues and rvalues The result of calling a function that does not return a reference is an rvalue. User defined operators are functions, and whether such operators expect or yield lvalues is determined by their parameter and return types. The standard says nothing in this paragraph, except that user-defined types and primitive types are the same. If the return of a function is not a reference, then it is not an l-value. There is however an interesting commentary on the same page: 47) Expressions such as invocations of constructors and of functions that return a class type refer to objects, and the implementation can invoke a member function upon such objects, but the expressions are not lvalues. So basically in your example: AMethod() = YourClass(); AMethod returns a user-defined type on which the function: AMethod().operator=(YourClass()); is executed. Still, it is not an l-value. In fact, you could have empty statements in C++, or statement that consist of an r-value only!: 5;;; // correct C++ code! EDIT2: Consider this example: if( &(YourClass() + YourClass()) == &YourClass() ) { .... } The expression &(YourClass() + YourClass()) must yield an l-value so the whole expression becomes correct. It compiles fine on VC but it gives this little warning: warning C4238: nonstandard extension used : class rvalue used as lvalue Obviously the above line was wrong by C++ standards but VC just allows it! Because you asked it so. First, a fresh instance of YourClass is returned by AMethod. Then, it is assigned another fresh instance. Of course in C++ you can say what ever you want. So, to prevent the assignment statement, just return const YourClass. In this case, the object becomes "readable" only: const YourClass AMethod(){ return YourClass();} This is the same in case you are overloading binary operators. For example, if you overload operator+ for a class, then you can do with const or without it. // '+' operator is defined as a friend operator not a member. friend YourClass operator+(const YourClass& lhs, const YourClass& rhs) { ... } If you did it that way, you could have meaningless statement like the following: (a + b) = c; Where the expression (a + b) is not useful because it represents only a value, not a variable we control, it produces a temp variable.
1,506,738
1,506,767
"corrupted double-linked list" on boost::function free()
I am going to try to ask this question without supplying too much source code because all the relevant bits add up to a bunch. The key (I think?) objects involved are using namespace o2scl; typedef MSMTModel<TASensor,PosModel,target2d,ovector,ovector_const_subvector> TA_MSMTModel; typedef MPC_funct_mfptr<MSMT_InitialState,TA_MSMTModel,MSMTFormation> MPC_TAFormation_mfptr; typedef boost::function<int (size_t, const ovector_base&, double&, TA_MSMTModel&)> TA_mfunct; TA_mfunct mf1 = boost::bind(&MPC_TAFormation_mfptr::mfn, f1, _1, _2, _3, _4); the boost::function mf1 is used as a callback function for a minimisation routine (o2scl::ool_mmin_spg) but I don't think the problem I am having is specific to that. The code runs with the calls to the ool_mmin_spg.mmin() function which makes use of mf1 as a callback and seems to run without errors. Then I get this lovely message * glibc detected * ./test: corrupted double-linked list: 0x0000000001e9fb20 *** followed by a backtrace and memory map. The relevant line of the backtrace seems to be #7 0x000000000041d32a in boost::detail::function::functor_manager, o2scl::ovector_const_subvector_tlate >, MSMTFormation>, unsigned long, o2scl::ovector_base_tlate const&, double&, dmect::MSMTModel, o2scl::ovector_const_subvector_tlate >&>, boost::_bi::list5, o2scl::ovector_const_subvector_tlate >, MSMTFormation> >, boost::arg<1>, boost::arg<2>, boost::arg<3>, boost::arg<4> > > >::manage (in_buffer=, out_buffer=warning: (Internal error: pc 0x41d270 in read in psymtab, but not in symtab.) I deduce that there is a problem freeing up memory from the boost::function, but other than that I am lost. Are there any pointers on trying to debug glibc "corrupted double-linked list" errors? I've found a few references on google but all have seemed to address very specific problems. Please let me know if more detailed code snips are required and thanks for your time!
Run the program through valgrind. That'll give you a stack trace when the memory gets corrupted (as well as a stack trace corresponding to the history of that piece of memory eg. where it was created or, if it was deleted, where it was destroyed).
1,506,835
1,506,951
What should be used to check identity in C++?
I have two pointers to objects and I want to test if they are the exact same object in the most robust manner. I explicitly do not want to invoke any operator == overloads and I want it to work no matter what base classes, virtual base classes and multiple inheritance is used. My current code is this: ((void*)a) == ((void*)b) And for my case this works. However, that doesn’t work for this case: class B1 {}; class B2 {}; class C : public B1, public B2 {} C c; B1 *a = &c; B2 *b = &c; Subbing in reinterpert_cast, static_cast or dynamic_cast doesn't work either. Particularly I'm hoping for something that ends up really simple and efficient. Ideally it wouldn't require any branch instructions to implement and would do something like, adjust the pointer to the start of the object and compare.
If your classes are genuinely exactly as given then it's impossible as there's not enough information available at runtime to reconstruct the required information. If they're actually polymorphic classes, with virtual functions, it sounds like dynamic_cast<void *> is the answer. It returns a pointer to the most derived object. Your check would then be dynamic_cast<void *>(a)==dynamic_cast<void *>(b). See paragraph 7 here: http://www.csci.csusb.edu/dick/c++std/cd2/expr.html#expr.dynamic.cast I suspect the usual dynamic_cast issues apply -- i.e., no guarantee it will be quick, and your classes will have to be polymorphic. This is not a feature I have used myself, I'm afraid -- but I have seen it suggested often enough by people who have that I infer it is widely-supported and works as advertised.
1,506,903
1,512,214
Custom front end and back end with Pantheios logging
Apologies if I'm missing something really obvious, but I'm trying to understand how to write a custom front end and back end with Pantheios. (I'm using it from C++, not C.) I can follow the purposes of the initialisation functions (I think) but I'm unsure about the others: pantheios_be_logEntry, pantheios_fe_getProcessIdentity and pantheios_fe_isSeverityLogged. In particular, I'm confused about the relationship between a front end and a back end. How do I make them communicate with each other?
Not sure I understand exactly what you don't understand, but maybe that's part of the problem. ;-) So I'll try my best and you let me know whether it's near or not. pantheios_fe_getProcessIdentity() is called once, when Pantheios is initializing. You need to return a string that identifies the process. (Actually, it identifies the link-unit; a term defined in Imperfect C++, written by Pantheios' creator, Matthew Wilson, which means the scope of link names, i.e. an executable program module or a dynamic library module.) pantheios_fe_isSeverityLogged() is called whenever a log statement is executed in application code. It returns non-zero to indicate that the statement should be processed and sent to the output (via the back-end). If it returns zero, no processing occurs. FWIU, this is the main reason why Pantheios is so fast. pantheios_be_logEntry() is called whenever a log statement is to be sent for output, when pantheios_fe_isSeverityLogged() has returned non-zero and the Pantheios core has processed the statement (forming all the arguments in your code into a single string). It sends the statement string to wherever it should go. For example, the be.fprintf back-end prints it to the console using fprint(). Once you grok these aspects, the second part of your question is where it gets interesting. When your front-end and back-end are initialized they get to create some context (e.g. a C++ object) that the Pantheios core holds for them, and gives them back each time it calls a front/back end API function. When you're customizing both, you can have them communicate via some shared context that they both know about, but which the Pantheios core does not (and should not) know about, beyond having an opaque handle (void*) to it. HTH
1,507,298
1,507,368
Solving An Equation in an Array
Im trying to figure out how i can solve an equation that has been stored in an array. I need some guidance on how to conquer such problem. here is my conditions i have an array int X[30]; and in there i have stored my desired equation: 5+6*20/4 as well, i couldnt store the operants (+ / - * ) so i used different identifiers for them like ( -1 -2 -3 -4 ) because there should not be a negative value in the equation. any help would be greatly appreciated thanks
Normally, you have to define the priority of each operation and process each of them one by one. First your expression is: '`[ 5,-1, 6,-4,20,-2, 4]`' Do all '/' first: '`[ 5,-1, 6,-4, 5,-1, 0]`' <- 20/ 4 = 5+0 Then, do all '*': '`[ 5,-1,30,-1, 0,-1, 0]`' <- 6* 5 = 30+0 Then, do all '-': '`[ 5,-1,30,-1, 0,-1, 0]`' <- Nothing Then, do all '+' (sum positive): '`[35,-1, 0,-1, 0,-1, 0]`' <- 5+30+0+0 = 35 + 0 + 0 ADDED: Here is the C code. void ShowArray(int pX[], int pLength) { int i; for(i = 0; i < pLength; i++) printf("%3d ", pX[i]); printf("\n"); }   void ShiftArray(int pX[], int pIndex, int pSkip, int pLength) { int i; for(i = pIndex; i < (pLength - pSkip); i++) pX[i] = pX[i + pSkip];   for(i = (pLength - pSkip); i < pLength; i++) pX[i] = 0; }   int main(void) { const int OPERCOUNT = 4; const int PLUS = -1; // -1 Do last const int SUBT = -2; const int MULT = -3; const int DIV = -4; // -4 Do first   int X[] = {5, PLUS, 6, MULT, 20, DIV, 4}; int XCount = 7;   ShowArray(X, XCount);   int i; for(i = OPERCOUNT; --i >= 0; ) { int OPER = -(i + 1); int j = 0; for(j = 0; j < XCount; j++) { int x = X[j]; if (x == OPER) { if (x == PLUS) X[j - 1] = X[j - 1] + X[j + 1]; else if (x == SUBT) X[j - 1] = X[j - 1] - X[j + 1]; else if (x == MULT) X[j - 1] = X[j - 1] * X[j + 1]; else if (x == DIV ) X[j - 1] = X[j - 1] / X[j + 1]; ShiftArray(X, j, 2, XCount); } }   ShowArray(X, XCount); }   int Sum = 0; int j; for(j = 0; j < XCount; j++) { int x = X[j]; if (x > 0) Sum += x; } printf("Result: %d\n", Sum); } And here is the result: 5 -1 6 -3 20 -4 4 5 -1 6 -3 5 0 0 5 -1 30 0 0 0 0 5 -1 30 0 0 0 0 35 0 0 0 0 0 0 Result: 35 This should works. Enjoy coding.
1,507,301
1,507,320
Getting FILEVERSION from Visual C++ Resource File
Are there some preprocessor keywords to use to access the FILEVERSION defined in my .rc file at compile time? I don't really want to add extra code to read the file information from the compiled product itself.
The preprocessor runs on the .RC file as well. Define the shared data in a header that is included by both the .RC and your source code. i.e., in foo.h: #define MY_PRODUCT_NAME Foo Then in the foo.rc: #include "foo.h" VS_VERSION_INFO VERSIONINFO // Many lines omitted VALUE "ProductName", MY_PRODUCT_NAME Then in foo.cpp: #include "foo.h" cout << MY_PRODUCT_NAME;
1,507,743
1,507,755
What's the rationale behind headers?
I don't quite understand the point of having a header; it seems to violate the DRY principle! All the information in a header is (can be) contained in the implementation.
It simplifies the compilation process. When you want to compile units independently, you need something to describe the parts that will be linked to without having to import the entirety of all the other files. It also allows for code hiding. One can distribute a header to allow others to use the functionality without having to distribute the implementation. Finally, it can encourage the separation of interface from implementation. They are not the only way to solve these problems, but 30 years ago they were a good one. We probably wouldn't use header files for a language today, but they weren't invented in 2009.
1,507,761
1,508,018
Preventing a complete rebuild using branches with GIT and Visual Studio 2005
One of the problem I faced when using branches in GIT was that it was very easy when switching branches to cause visual studio 2005 to cause a complete rebuild of the source because of the time/date being changed when switching branches. My typical layout is this. svn/remote master test When switch between either the test and the master branch even though both of them shared exactly the same timestamp on the project. It would cause visual studio 2005 to rebuild the complete project again. To resolve this issue, my solution was to create another GIT repository but to make a new repository that pulled from the main repository c:/myPrimary 'test' branch. This way, even though both master and test branches had their own folder via the extra repository this resolved having to do a complete recompilation of the source code when switching between the two. Just checking if anyone else have had this problem and the solution they have come up with resolving it. Please note, a complete recompilation of the source code is in the area of 20 minutes.
git only touches files which actually change when switching branches, so only translation units that include files that are different between the two branches should have their timestamp updated when switching between the two branches. Visual Studio 2005 is generally very good at incremental builds, but it is very easy in C++ to build up overly inter-dependent include paths if you aren't careful to manage a project's complexity. Have you tried analysing your source file dependencies to see if a set of frequently changed header files is causing a large subset of object files to be rebuilt?
1,508,327
1,508,760
Loading Qt plugins when linking to Qt statically?
I'm trying to use SVG graphics in QIcons. I have a static library that contains all my graphics resources, and a method in that static library that returns QIcons pre-loaded with the correct graphics. I'm trying to do this: QIcon icon(":/icons/find.svg"); I have verified that that resources has been loaded by listing it with QDir: qDebug() << QDir(":/icons/").entryList(); However, the SVG icon is not being shown. When I change the icon loading code to this: QIcon icon(":/icons/find.png"); everything works correctly. The problem seems to be that the SVG plugin never gets loaded. I can get a list of supported image types, which contains: ("bmp", "pbm", "pgm", "png", "ppm", "xbm", "xpm") but no mention of SVG. I've made sure I'm using the SVG module in both my static library .pro file, and my main application .pro file. Edit: It seems the problem is that I am linking to Qt statically, and thus the plugins are all static libs. The documentation for QPluginLoader states that: Note that the QPluginLoader cannot be used if your application is statically linked against Qt. In this case, you will also have to link to plugins statically. You can use QLibrary if you need to load dynamic libraries in a statically linked application. Yet statically linking to these plugins seems to do nothing ( the list of supported image formats does not grow). Edit2: Also, linking to Qt dynamically (after rebuilding my whole app) makes the code above work perfectly. However, I want to link to Qt statically, so the question looks now to be more about loading Qt plugins when linking to Qt statically and less about icons in general. I will update the post title to reflect this.
You need to use Q_IMPORT_PLUGIN. See the documentation here: https://doc.qt.io/qt-5/qtplugin.html#Q_IMPORT_PLUGIN