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,122,268
1,122,593
How to construct a static global variable in C++
I'm having some trouble compiling/linking a set of classes, several of them dealing with a common global variable. Basically, I declare and define a extern variable foo in class A and access/update it in classes B and C. The relevant code looks like this: A.h extern string foo; // declare it <=== compiler error "storage class specified for foo" B.cpp include A.h string foo; // define it main () { ... foo = "abc"; } C.cpp include A.h cout << foo; // print it My current error is "storage class specified for foo". But, I'm wondering if this is the correct approach. Should I be using a static variable? Any help much appreciated, as I've been on this for at least an hour by now.
In A.h have you actually got the extern declaration within the actual class A? Your question currently says this in words but then your code snippet suggests it is at file level. The only way I can get the error you are talking about i.e. "storage class specified for foo" is for the following in A.h: class A { public: extern std::string foo; }; Perhaps this is your problem? Edit: Looking at your own answer I think this is what you've done. You want to replace extern with static and then define that static in A.cpp with a line like std::string A::foo; You can then subsequently access it in other places as A::foo eg. std::cout << A::foo;
1,122,749
1,123,265
Implementing drag and drop with QT 4.5 using QT Creator environment
We're about to commit to Qt and C++ (sigh) to do some cross-platform development. The latest version of Qt 4.5 seems very nice as does the QT Creator IDE, which although simple compared to other IDEs, is a good way to get started. I'm trying to understand how to do drag and drop into QT widgets from the "outside" world. As far as I can tell from the documentation, you're supposed to subclass a widget that you want to have respond to drop events and override some methods (the dragEnterEvent and dropEvent member functions) for that widget. But if I use the Qt Creator tool, I don't seem to have any access to the classes of the widgets that I have created using the GUI form builder and so I can't subclass them. WHat's the secret? Thanks in advance, D
Someone on my team figured it out ---- turns out there is an option to "Promote" a widget, meaning you can subclass it to something else and then override the needed methods with no pain. Seems to me it would have been more obvious if it said "Subclass widget..." rather than "Promote" but that's OK. This QT Creator is a very nice piece of work.
1,122,785
1,122,794
How to force Visual Studio preprocessor case sensitivity with #includes?
If you have a header file named ThisIsAHeaderFile.h, the following will still locate the file in Visual Studio: #include <ThisIsAheaderFile.h> Is there a way to enforce case sensitivity so that the #include will result in an error?
You can't, because the Windows file system is itself case-insensitive. If you could get into a situation where you had both RICHIE.h and richie.h, it might make sense to control case sensitivity, but you can't.
1,122,938
1,123,048
Undefined reference - C++ linker error
I'm getting an Undefined reference error message, on this statement: GlobalClass *GlobalClass::s_instance = 0; Any ideas? Code is shown below: ================================================ #ifndef GLOBALCLASS_H_ #define GLOBALCLASS_H_ #include <string> class GlobalClass { public: std::string get_value(); void set_value(std::string); static GlobalClass *instance(); static GlobalClass *s_instance; private: std::string m_value; }; #endif /* GLOBALCLASS_H_ */ =============================================== #include <string> #include "GlobalClass.h" /* GlobalClass(int v = 0) { m_value = v; } */ static GlobalClass *s_instance; std::string GlobalClass::get_value() { return m_value; } void GlobalClass::set_value(std::string v) { m_value = v; } static GlobalClass *instance() { if (!s_instance) s_instance = new GlobalClass; return s_instance; } =========================================================== #include <iostream> #include "GlobalClass.h" using namespace std; int main() { GlobalClass::s_instance = 0; std::string myAddress = "abc"; GlobalClass::instance()->set_value(myAddress); \\ <=== compiler error std::cout << "====>address is is " << GlobalClass::instance()->get_value() << std::endl; return 0; }
Are you trying to implement a Singleton class? Ie. You want only a single instance of of the class, and you want that instance available to anyone who includes the class. I think its commonly known as a Singleton, the following example works as expected: Singleton.h: #include <string> class Singleton { public: static Singleton* instance() { if ( p_theInstance == 0 ) p_theInstance = new Singleton; return p_theInstance; } void setMember( const std::string& some_string ) { some_member = some_string; } const std::string& get_member() const { return some_member; } private: Singleton() {} static Singleton* p_theInstance; std::string some_member; }; Singleton.cpp: Singleton* Singleton::p_theInstance = 0; main.cpp: #include <string> #include <iostream> #include "Singleton.h" int main() { std::string some_string = "Singleton class"; Singleton::instance()->setMember(some_string); std::cout << Singleton::instance()->get_member() << "\n"; } Note that the constructor is private, we don't want anyone to be creating instances of our singleton, unless its via the 'instance()' operator.
1,123,013
1,124,020
Undefined reference error message - C++
Possible Duplicate: Undefined reference - C++ linker error Now, I'm getting an "Undefined reference error message to 'GlobalClass::s_instance', and 'GlobalClass::instance()', respectively on these statements: GlobalClass *GlobalClass::s_instance = 0; GlobalClass::instance()->set_value(myAddress); \\ <== undefined reference std::cout << "====>address is is " << GlobalClass::instance()->get_value() Any ideas? The code is shown below: ================================================ #ifndef GLOBALCLASS_H_ #define GLOBALCLASS_H_ #include <string> class GlobalClass { public: std::string get_value(); void set_value(std::string); static GlobalClass *instance(); static GlobalClass *s_instance; private: std::string m_value; }; #endif /* GLOBALCLASS_H_ */ =============================================== #include <string> #include "GlobalClass.h" /* GlobalClass(int v = 0) { m_value = v; } */ static GlobalClass *s_instance; std::string GlobalClass::get_value() { return m_value; } void GlobalClass::set_value(std::string v) { m_value = v; } static GlobalClass *instance() { if (!s_instance) s_instance = new GlobalClass; return s_instance; } =========================================================== #include <iostream> #include "GlobalClass.h" using namespace std; int main() { GlobalClass::s_instance = 0; \\ <== undefined reference std::string myAddress = "abc"; GlobalClass::instance()->set_value(myAddress); \\ <== undefined reference std::cout << "====>address is is " << GlobalClass::instance()->get_value() \\ <== undefined reference << std::endl; return 0; }
Further to Alex Black's response, its complaining that the GlobalClass::instance() function does not have an implementation. Which it doesn't: static GlobalClass *instance() { if (!s_instance) s_instance = new GlobalClass; return s_instance; } That really ought to be: GlobalClass *GlobalClass::instance() { if (!s_instance) s_instance = new GlobalClass; return s_instance; } Don't forget that even though it is static it is still a member function!
1,123,044
1,123,159
When should your destructor be virtual?
Possible Duplicate: When to use virtual destructors? When should your C++ object's destructor be virtual?
You need virtual destructor when at least one of class methods is virtual. This is because the reason for virtual method is that you want to use polymorphism. Meaning you will call a method on the base class pointer and you want the most derived implementation - this is the whole point of polymorphism. Now if you did not have virtual destructor and through the pointer to base class you call destructor you end up calling base class destructor. In this case you want polymorphism to work on your destructor as well, e.g. through calling destructor on your base class you want to end up calling destructor of your most derived class not your base class. class A { virtual void f() {} ~A() {} } class B : public A { void f() {} ~B() {} } A * thing = new B(); thing->f(); // calls B's f() delete thing; // calls ~A(), not what you wanted, you wanted ~B() having ~A() virtual turns on polymorphism virtual ~A() {} So when you now call delete thing; ~B() will be called. You would declare virtual destructors when you design class as an interface e.g. you expect it to be extended or implemented. A good practice in that case is to have a interface class (in the sense of Java interfaces) with virtual methods and virtual destructor and then have concrete implementation classes. You can see that STL classes don't have virtual destructors so they are not supposed to be extended (e.g. std::vector, std::string ...). If you extend std::vector and you call destructor on base class via pointer or reference you will definitely not call your specialized class destructor which may lead to memory leaks.
1,123,080
1,123,116
Why do we need typename here?
template<class T> class Set { public: void insert(const T& item); void remove(const T& item); private: std::list<T> rep; } template<typename T> void Set<T>::remove(const T& item) { typename std::list<T>::iterator it = // question here std::find(rep.begin(),rep.end(),itme); if(it!=rep.end()) rep.erase(it); } Why the typename in the remove() is needed?
In general, C++ needs typename because of the unfortunate syntax [*] it inherits from C, that makes it impossible without non-local information to say -- for example -- in A * B; whether A names a type (in which case this is a declaration of B as a pointer to it) or not (in which case this is a multiplication expression -- quite possible since A, for all you can tell without non-local information, could be an instance of a class that overloads operator* to do something weird;-). In most cases the compiler does have the non-local information needed to disambiguate (though the unfortunate syntax still means the low-level parser needs feedback from the higher-level layer that keeps the symbol table info)... but with templates it doesn't (not in general, though in this specific case it might be technically illegal to specialize a std::list<T> so that its ::iterator is NOT a type name;-). [*] not just my opinion, but also the opinion of Ken Thompson and Rob Pikes, currently my colleagues, who are busy designing and implementing a new programming language for internal use: that new programming language, while its syntax is mostly C-like, does NOT repeat C's syntax design errors -- it the new language (like e.g. in good old Pascal), syntax is sufficient to distinguish identifiers that must name a type from ones that must not;-).
1,123,115
1,125,750
Boost Graph Library and Visitors
I'm writing a library for manipulating bond graphs, and I'm using the Boost Graph Library to store the data for me. Unfortunately, I can't seem to figure out how to implement a proper visitor pattern using it, as you can't subclass out vertices - you must rely on 'properties' instead. The visitor framework provided in the library seems heavily geared towards working with certain algorithms where vertices are all of the same type, but store different information. In my problem, the vertices are of differing types and store differing types of information - some vertices are resistors, while some are capacitors, etc. How do I go about writing a visitor pattern that works based on a property of a vertex, instead of the vertex itself? My only thought so far has been to write a small class to represent the type of an object that points back to the original vertex that I need to get the graph information. However, this seems very kludgy, and evil to work with.
What do you mean, you can't subclass out vertices? You can use your own vertex class, it's just a matter of specifying it in the Graph typedef. You can even use members as properties when working with BGL algorithms. As for the other way around (which is harder IMO), you need to create a vertex property list and access it using a vertex descriptor... I think. Edit: You specify vertex/edge classes when defining your graph type: struct Vertex { double some_property; }; struct Edge { double weight; }; typedef boost::adjacency_list< boost::listS, boost::vecS, boost::undirectedS, Vertex, Edge > Graph; //sorry about the formatting Graph g; From where on g[vertex_descriptor] should return a reference to Vertex, e.g.: //add 100 vertices for (int i=0; i<100; ++i) { Graph::vertex_descriptor v = add_vertex(g); g[v].some_property = -1.0; } //zero some_property for all vertices for (Graph::vertex_iterator i = vertices(g).first; i != vertices(g).second; ++i) { g[*i].some_property = 0.0; } I couldn't find my visitor code making use of these properties but I did find the relevant part of the BGL documentation: 1) The part about Internal Properties, which recommends you use instead: 2) Bundled Properties The second link seems to have a Boost function making use of bundled properties using a member pointer. Does this help?
1,123,455
1,123,493
Should every C++ programmer read the ISO standard to become professional?
Should every C++ programmer read the ISO standard to become professional?
No. C++ standard is more like a dictionary - something where you look up specific things that concern you at any given moment. It doesn't make a good (or useful) reading if you treat it as a simple book to read from beginning to end. If the question were whether every professional C++ programmer should have an ISO standard at hand, and use it for reference as needed, then I'd say "yes".
1,123,587
1,123,646
c++ std::fstream behaviour on MacOS
On MacOS with gcc4.2 should the following code create a new file if none exists? #include <fstream> void test () { std::fstream file ("myfile.txt", std::ios::in | std::ios::out); } By my logic it should, either open up an existing file for read/writing or create a new empty file for read/writing. But the behaviour I get is that it will not create a new file if 'myfile.txt' does not exist. How do I get the same behavior as fopen("myfile.txt", "r+"); ? Furthermore, #include <fstream> void test () { std::ofstream file ("myfile.txt", std::ios::in | std::ios::out); } Will always truncate an existing file... Is this the standard behavior?
First of all, I have no idea why you think that fopen("r+") creates a file if it doesn't exist - according to ISO C & C++, it does not, it just opens an existing file for read/write. If you want to create a file with fopen, you use "w+". For streams, you just specify trunc: std::ofstream file ("myfile.txt", std::ios::in | std::ios::out | std::ios::trunc); However, both this and fopen("w+") will truncate the file. There's no standard way to open the file without truncating if it exists, but create it if it does not exist in a single call. At best you can try to open, check for failure, and then try to create/truncate; but this may lead to a race condition if file is created by another process after the check but before truncation. In POSIX, you can use open with O_CREAT and without O_TRUNC.
1,123,700
1,123,730
Projects for C++ Beginner/Intermediate?
I really want to learn more about C++. I know the basics, and I know the concepts, and I have even been able to create C++ projects myself, but my problem is being able to view, fix, and add to code I haven't written myself. I have looked at some open source projects on sourceforge, etc, but many of them are so big or there are soooo many projects available until I don't know what to do. Are there any "small or simple" projects or tasks in C++ that will allow me to extend my knowledge of C++ by use of hands on experience?
If you are already able to create own projects, I think the best way to learn how to read&change someone's code is to get job in software company. They even will pay for it :)
1,123,725
1,123,759
Why should default parameters be added last in C++ functions?
Why should default parameters be added last in C++ functions?
To simplify the language definition and keep code readable. void foo(int x = 2, int y); To call that and take advantage of the default value, you'd need syntax like this: foo(, 3); Which was probably felt to be too weird. Another alternative is specifying names in the argument list: foo(y : 3); A new symbol would have to be used because this already means something: foo(y = 3); // assign 3 to y and then pass y to foo. The naming approach was considered and rejected by the ISO committee because they were uncomfortable with introducing a new significance to parameter names outside of the function definition. If you're interested in more C++ design rationales, read The Design and Evolution of C++ by Stroustrup.
1,123,880
1,123,886
Am I using new operator correctly?
I have the following pointer. char **x = NULL; x is will point to an array of pointers. So is the following code correct? x = new (nothrow) (*char)[20]; and we will dealocate it using delete[] x; Is x = (char **) malloc(sizeof(char **) * 20); and x = new (nothrow) (*char)[20]; equivalent?
No, that code has syntax errors. The asterisk goes after the type name, to form a pointer to that type. So it's: char* not: *char It's weird that you have this right in the "C-style" example using malloc(), but not in C++. As many commenters have kindly enough pointed out, there are other issues with the malloc() and its use of sizeof, though. But at least it got the type name right. Personally I'm against repeating type names in malloc() calls if at all possible, so I would write that version like this, to allocate a dynamic array of 20 character pointers: char **x; x = malloc(20 * sizeof *x); This way: Should be read as "20 times the size of whatever x points at", i.e. 20 times the size of a single char * pointer. Contains the magical constant 20 in one place only. Doesn't repeat any part of the type, if you were to change to wchar_t **x this would still work, and not by chance. Is written in C, since I felt that is more natural when discussing malloc(). In C++, you need to cast the return value. In C, you should never do that.
1,123,975
1,124,046
How to override member of base class after inheritance in C++
i have this : class A { public : A(int i ) : m_S(i) { m_Pa = new Foo(*this) ; } private : int m_S ; Foo* m_Pa; } and derived class class B : public A { public : B() : A (242) { // here i like to override the A class m_Pa member but i don't know how to do it right } }
your m_Pa should be protected than you can call like: B() : A (242), m_Pa(12) { } or B() : A (242) { m_PA = 55 } or you should make a public or protected function which changes m_Pa class A { public : A(int i ) : m_S(i) { m_Pa = new Foo(*this) ; } void setPA(int val) { m_PA = val; }
1,124,129
1,124,166
High-level HTTP client library for native C/C++ in Win32
Are there no "high-level" HTTP libraries for native C/C++ in Win32 or am I just looking in the wrong places? By "high-level" I mean an API that lets me do HTTP web requests/responses in C++ with "about the same" abstraction level as the .NET framework (but note that using C++/CLI is not an option for me). How to do something like this (with about the same amount of code) in C/C++ in Win32 without using .NET? As a reference, I include a code sample to show how I'd do it in C#. byte[] fileBytes = null; bool successfulDownload = false; using (WebClient client = new WebClient()) { WebProxy proxy = WebProxy.GetDefaultProxy(); client.Proxy = proxy; tryAgain: try { fileBytes = client.DownloadData(fileUrl); successfulDownload = true; } catch (WebException wEx) { if (wEx.Response != null && wEx.Response is HttpWebResponse) { string username = null, password = null; bool userCanceled = false; HttpStatusCode statusCode = ((HttpWebResponse)wEx.Response).StatusCode; switch (statusCode) { case HttpStatusCode.ProxyAuthenticationRequired: // This is just a convenience function defined elsewhere GetAuthenticationCredentials(fileUrl, true, out username, out password, out userCanceled); if (!userCanceled) { client.Proxy.Credentials = new NetworkCredential(username, password); goto tryAgain; } break; case HttpStatusCode.Unauthorized: // This is just a convenience function defined elsewhere GetAuthenticationCredentials(fileUrl, false, out username, out password, out userCanceled); if (!userCanceled) { client.Credentials = new NetworkCredential(username, password); goto tryAgain; } break; } } } }
Win32 provides the Internet* functions. http://msdn.microsoft.com/en-us/library/aa385473(VS.85).aspx You'll need to do an (IIRC, I haven't touched these APIs in over 10 years) InternetOpenURL and InternetReadFile.
1,124,223
1,153,840
simple rtsp broadcast example source
I want to broadcast the screen (not a static screen) of my program using rtsp/rtp since this way a mobile phone (at least the more recent ones) can view the stream. I'm looking for a simple example program which takes the frames I offer, encodes it with a codec and then sends this (using rtsp) to any clients attached. I've looked on the net and all I can find so far are full fledged opensource media servers (like darwin) which are just too complex to use as an example any help appreciated! R p.s. sending jpegs to the mobile phone is really not an option since this is non standard and would require a mobile app to be installed to interpret the 'stream'. p.s.2 C, C++ or C# would be fine.
this seems to be pretty much what I was looking for: live555.com Useful libraries and code examples of how to stream stuff from your own app R
1,124,232
1,124,362
Getting started guide for Boost.Spirit?
I've been looking recently at Boost.Spirit (the version included in Boost 1.39), however I'm quite confused from the docs alone. What I'm looking for is for an example of a toy language implemented with Boost.Spirit -- something along the lines of a tiny Javascript or Lua or so, where you basically create an AST and process is. I'd be happy if it just supports function/variable definitions and the basic operators, I just want to see how you would create a normal AST using Boost.Spirit, and how to implement basic rules like identifiers, declarations, etc. So far, I've tried the calculator example, but it's unclear for me how to implement a larger grammar with Spirit. The mini_c example which is bundled on the other hand looks quite complicated already, and it's not too well documented. Is there some easy to understand guide to Boost.Spirit out there, or a book maybe?
An introductory article from CP A JSON parser implemented using Boost.Spirit from CodeProject Spirit Application Repository
1,124,340
1,129,672
Any ideas why QHash and QMap return const T instead of const T&?
Unlike std::map and std::hash_map, corresponding versions in Qt do not bother to return a reference. Isn't it quite inefficient, if I build a hash for quite bulky class? EDIT especially since there is a separate method value(), which could then return it by value.
const subscript operators of STL containers can return a reference-to-const because they flat out deny calls to it with indexes that do not exist in the container. Behaviour in this case is undefined. Consequently, as a wise design choice, std::map doesn't even provide a const subscript operator overload. QMap tries to be a bit more accommodating, provides a const subscript operator overload as syntactic sugar, runs into the problem with non-existing keys, again tries to be more accomodating, and returns a default-constructed value instead. If you wanted to keep STL's return-by-const-reference convention, you'd need to allocate a static value and return a reference to that. That, however, would be quite at odds with the reentrancy guarantees that QMap provides, so the only option is to return by value. The const there is just sugar coating to prevent some stupid mistakes like constmap["foo"]++ from compiling. That said, returning by reference is not always the most efficient way. If you return a fundamental type, or, with more aggressive optimisation, when sizeof(T)<=sizeof(void*), return-by-value often makes the compiler return the result in a register directly instead of indirectly (address to result in register) or—heaven forbid—on the stack. The other reason (besides premature pessimisation) to prefer pass-by-const-reference, slicing, doesn't apply here, since both std::map and QMap are value-based, and therefore homogeneous. For a heterogeneous container, you'd need to hold pointers, and pointers are fundamental types (except smart ones, of course). That all said, I almost never use the const subscript operator in Qt. Yes, it has nicer syntax than find()+*it, but invariably, you'll end up with count()/contains() calls right in front of the const subscript operator, which means you're doing the binary search twice. And then you won't notice the miniscule differences in return value performance anyway :) For value() const, though, I agree that it should return reference-to-const, defaulting to the reference-to-default-value being passed in as second argument, but I guess the Qt developers felt that was too much magic.
1,124,466
1,124,549
hash_map and map which is faster? less than 10000 items
vs2005 support ::stdext::hash_map ::std::map. however it seems ::stdext::hash_map's insert and remove OP is slower then ::std::map in my test. ( less then 10000 items) Interesting.... Can anyone offored a comparision article about them?
It is not just about insertion and removal. You must consider that memory is allocated differently in a hash_map vs map and you every time have to calculate the hash of the value being searched. I think this Dr.Dobbs article will answer your question best: C++ STL Hash Containers and Performance
1,124,534
1,124,539
Computing length of array
I have a C++ array declared as mentioned below: CString carray[] = { "A", "B", "C", "D", "E" } I want to determine the length of carray at runtime. I am doing: int iLength = sizeof(carray)/sizeof(CString); Is this correct?
Yes. In case the declared element type ever changes, you could also write int iLength = sizeof(carray)/sizeof(carray[0]);
1,124,571
1,124,588
Get list of static libraries used in an executable
Since ldd lists only the dynamic libraries, is there a way to extract the information about the static libraries used to create the executable?
ldd <exe filename> shows dynamically linked libraries nm <exe filename> shows the symbols in the file. To see which symbols come from static libraries requires running nm against those libraries to get a list of the symbols (functions, etc.) in them, then comparing them to what your list of symbols from nm <exe filename>. You compare lists with the comm command. See man comm for details. This was taken from this forum here.
1,124,634
1,124,759
Call destructor and then constructor (resetting an object)
I want to reset an object. Can I do it in the following way? anObject->~AnObject(); anObject = new(anObject) AnObject(); // edit: this is not allowed: anObject->AnObject(); This code is obviously a subset of typical life cycle of an object allocated by in placement new: AnObject* anObject = malloc(sizeof(AnObject)); anObject = new (anObject) AnObject(); // My step 2. // ... anObject->~AnObject(); // My step 1. free(anObject) // EDIT: The fact I used malloc instead of new doesn't carry any meaning The only thing that's changed is the order of constructor and destructor calls. So, why in the following FAQ all the threatening appear? [11.9] But can I explicitly call a destructor if I've allocated my object with new? FAQ: You can't, unless the object was allocated with placement new. Objects created by new must be deleted, which does two things (remember them): calls the destructor, then frees the memory. FQA: Translation: delete is a way to explictly call a destructor, but it also deallocates the memory. You can also call a destructor without deallocating the memory. It's ugly and useless in most cases, but you can do that. The destructor/constructor call is obviously normal C++ code. Guarantees used in the code directly result from the in placement new guarantees. It is the core of the standard, it's rock solid thing. How can it be called "dirty" and be presented as something unreliable? Do you think it's possible, that the in-placement and non-in-placement implementation of new are different? I'm thinking about some sick possibility, that the regular new can for example put size of the memory block allocated before the block, which in-placement new obviously would not do (because it doesn't allocate any memory). This could result in a gap for some problems... Is such new() implementation possible?
Don't get sucked in by the FQA troll. As usual he gets the facts wrong. You can certainly call the destructor directly, for all objects whether they are created with placement new or not. Ugly is in the eye of the beholder, it is indeed rarely needed, but the only hard fact is that both memory allocation and object creation must be balanced. "Regular" new/delete simplifies this a bit by tying memory allocation and object creation together, and stack allocation simplifies it even further by doing both for you. However, the following is perfectly legal: int foo() { CBar bar; (&bar)->~CBar(); new (&bar) CBar(42); } Both objects are destroyed, and the stack memory is automatically recycled too. yet unlike the FQA claims, the first call of the destructor is not preceded by placement new.
1,124,726
1,124,733
Visual Studio 2008 build errors
I'm trying to compile an old project that was originally designed for Visual Studio 2008 SP0 (I'm using SP1 now). I'm getting these errors. Error 51 error LNK2019: unresolved external symbol "unsigned long __cdecl GetDeviceState(enum DEVICES_ENUM,enum DEVICE_STATE_ENUM &,int &)" (?GetDeviceState@@YAKW4DEVICES_ENUM@@AAW4DEVICE_STATE_ENUM@@AAH@Z) referenced in function _Get1394DeviceStatus Raw1394api.obj raw1394api Error 52 error LNK2019: unresolved external symbol "unsigned long __cdecl SetDeviceState(enum DEVICES_ENUM,enum DEVICE_STATE_ENUM,int &,int &)" (?SetDeviceState@@YAKW4DEVICES_ENUM@@W4DEVICE_STATE_ENUM@@AAH2@Z) referenced in function _Set1394DeviceStatus Raw1394api.obj raw1394api Error 53 error LNK2019: unresolved external symbol "bool __cdecl InstallDevice(wchar_t *)" (?InstallDevice@@YA_NPA_W@Z) referenced in function _InstallDriver Raw1394api.obj raw1394api Error 54 error LNK2019: unresolved external symbol "bool __cdecl UninstallDevice(void)" (?UninstallDevice@@YA_NXZ) referenced in function _UninstallDriver Raw1394api.obj raw1394api Error 55 fatal error LNK1120: 4 unresolved externals f:\InfoSelect My Documents\Zurvan on Windows\raw1394 for Windows by Dmitry\test\raw1394src\Debug\raw1394api.dll raw1394api
I would suggest to check the files mentioned in the last row.
1,125,349
1,125,553
How do I set the executable attributes with qmake for a c++ project?
I use buildbot to compile my Qt/C++/nmake project. I would like to add the version number to the executable and the company details (on the properties of the file). Does anybody know where I can set this information? Note: I am using buildbot not Visual Studio so I need a command line way of doing this.
Unless your version will remain static (i.e. you are only reporting a major build versions or you don't incorporate the version control revision into your version number) you will likely want the version to be generated as part of the build. This could be done in the pro file as another answer indicated but this would mean having to modify the pro file which is likely also checked into your repository. In this case, the best solution is a Windows resource file. This will also allow you to specify the other information you requested (company info, etc.) which I am not sure if you can do via the pro file. MSDN: About Windows Resource Files MSDN: Example Windows Resource File (Example is at the bottom of the page. Note the comments) Then you can include it as part of the project by setting the RC_FILE variable in your pro file. RC_FILE = application.rc Qt : qmake : RC_FILE Another example of a windows resource file can be found in the Google Chrome Repository. There they have an rc file for the application that references another rc file for the version information. I assume that part of the build process generates this version rc file from the template. /app directory Chrome.exe rc file Template for chrome rc version file
1,125,412
1,125,699
How to do an active sleep?
I am running some profiling tests, and usleep is an useful function. But while my program is sleeping, this time does not appear in the profile. eg. if I have a function as : void f1() { for (i = 0; i < 1000; i++) usleep(1000); } With profile tools as gprof, f1 does not seems to consume any time. What I am looking is a method nicer than an empty while loop for doing an active sleep, like: while (1) { if (gettime() == whatiwant) break; }
What kind of a system are you on? In UNIX-like systems you can use setitimer() to send a signal to a process after a specified period of time. This is the facility you would need to implement the type of "active sleep" you're looking for. Set the timer, then loop until you receive the signal.
1,126,071
1,126,079
Accessing members of an array of structures in C++
Working through C++ Primer Plus and am trying to cin data to a dynamically allocated array of structures. One of the items is a char array. How do I write to these struct members? Posting code of my wrong attempt so you can see what I'm trying to do. #include <iostream> using namespace std; struct contributions { char name[20]; double dollars; }; int donors; int main() { cout << "How many contributors will there be?\n"; cin >> donors; contributions * ptr = new contributions[donors]; for(int i = 0; i <= donors; i++) { cout << "Enter donor name #" << i+1 << ": \n"; cin >> ptr->contributions[i].name; cout << "Enter donation amount: \n"; cin >> ptr->contributions[i].dollars; } Thanks in advance!
Try using std::string instead of char[20] for name and the sample should work just fine. struct contributions { std::string name; double dollars; }; also change the access to ptr[i].name
1,126,118
1,126,146
where can I find a good boost reference?
I'd like to have a good up-to-date reference for boost by my side, and the only books I found are the following: Beyond the C++ Standard Library: An Introduction to Boost The C++ Standard Library Extensions: A Tutorial and Reference Both books are somewhat dated, and I am sure boost has been evolving. Obviously I can just use a direct source of Boost website. Is it enough to just use the website to learn and reference boost libraries? What If I am one of those folks who prefers hardcover books? Which one would you recommend? Thanks --Edit-- Does anyone know of online video tutorials on Boost, as well as text turials?
Try this one out: http://man.leftworld.net/develop/asio/reference/index.html http://alexott.blogspot.com/search/label/boost http://www.boost.org/doc/ http://torjo.com/tobias/ http://docs.huihoo.com/boost/1-33-1/libs/multi_index/doc/reference/index.html
1,126,445
1,126,455
Why does strlen() return a 64-bit integer? Am i missing something?
When compiling a 64bit application, why does strlen() return a 64-bit integer? Am i missing somthing? I understand that strlen() returns a size_t type, and by definition this shouldn’t change, but... Why would strlen need to return a 64-bit integer? The function is designed to be used with strings. With that said: Do programmers commonly create multi-gigabyte or multi-terabyte strings? If they did, wouldn’t they need a better way to determine the string length than searching for a NULL character? I think this is ridiculous, in fact, maybe we need a StrLenAsync() function with a callback just to handle the ultra long process for searching for the NULL in the 40TB string. Sound stupid? Yea, well strlen() returns a 64-bit integer! Of course, the proposed StrLenAsync() function is a joke.
It looks like, when compiling for a 64-bit target, size_t is defined as 64-bit. This makes sense, since size_t is used for sizes of all kinds of objects, not just strings.
1,126,730
1,126,742
How to find the width of a String (in pixels) in WIN32
Can you measure the width of a string more exactly in WIN32 than using the GetTextMetrics function and using tmAveCharWidth*strSize?
Try using GetTextExtentPoint32. That uses the current font for the given device context to measure the width and height of the rendered string in logical units. For the default mapping mode, MM_TEXT, 1 logical unit is 1 pixel. However, if you've changed the mapping mode for the current device context, a logical unit may not be the same as a pixel. You can read about the different mapping modes on MSDN. With the mapping mode, you can convert the dimensions returned to you by GetTextExtentPoint32 to pixels.
1,126,812
1,126,837
Class issue, adding a day
I'm trying to make the add_day function work, but I'm having some trouble. Note that I can't make any changes to the struct (it's very simplistic) because the point of the exercise is to make the program work with what's given. The code is #include "std_lib_facilities.h" struct Date{ int y, m, d; Date(int y, int m, int d); void add_day(int n); }; void Date::add_day(int n) { d+=n; } ostream& operator<<(ostream& os, const Date& d) { if(d.m<1 || d.m>12 || d.d<1 || d.d>31) cout << "Invalid date: "; return os << '(' << d.y << ',' << d.m << ',' << d.d << ')'; } int main() { Date today(1978,6,25); today.add_day(1); cout << today << endl; keep_window_open(); } I'm getting a linker error that says undefined reference to Date::Date(int,int,int), but I can't figure out what's wrong. It seems like it's something to do with the Date constructor, but I'm not sure what. I'd also like to add in a line of code for tomorrow like Date tomorrow = today.add_day(1); but I've got a feeling that since add_day is a void type there will be a conversion issue. Any help would be appreciated - thanks. P.S. Don't worry about adding days at the end of the month. It's something that's going to be implemented later.
The linker error is because you are not defining the constructor. Date::Date( int yr, int mo, int day ) : y(year), m(month), d(day) { } For the add_day question: you are correct that you need to change the return type. It should return a Date object. You can construct a new Date object and return it with the day value incremented or just increment the day value and return *this.
1,126,877
1,126,990
Edit the frame rate of an avi file
Is it possible to change the frame rate of an avi file using the Video for windows library? I tried the following steps but did not succeed. AviFileInit AviFileOpen(OF_READWRITE) pavi1 = AviFileGetStream avi_info = AviStreamInfo avi_info.dwrate = 15 EditStreamSetInfo(dwrate) returns -2147467262.
I'm pretty sure the AVIFile* APIs don't support this. (Disclaimer: I was the one who defined those APIs, but it was over 15 years ago...) You can't just call EditStreamSetInfo on an plain AVIStream, only one returned from CreateEditableStream. You could use AVISave, then, but that would obviously re-copy the whole file. So, yes, you would probably want to do this by parsing the AVI file header enough to find the one DWORD you want to change. There are lots of documents on the RIFF and AVI file formats out there, such as http://www.opennet.ru/docs/formats/avi.txt.
1,127,326
1,134,243
Advise HTMLElementEvents2 sink (MSDN website)
From the msdn website void CMyClass::ConnectEvents(IHTMLElement* pElem) { HRESULT hr; IConnectionPointContainer* pCPC = NULL; IConnectionPoint* pCP = NULL; DWORD dwCookie; // Check that this is a connectable object. hr = pElem->QueryInterface(IID_IConnectionPointContainer, (void**)&pCPC); if (SUCCEEDED(hr)) { // Find the connection point. hr = pCPC->FindConnectionPoint(DIID_HTMLElementEvents2, &pCP); if (SUCCEEDED(hr)) { // Advise the connection point. // pUnk is the IUnknown interface pointer for your event sink hr = pCP->Advise(pUnk, &dwCookie); if (SUCCEEDED(hr)) { // Successfully advised } pCP->Release(); } pCPC->Release(); } } How do I get the pUnk pointer? I have defined CComObject *pUnk as a global variable and initialize it as CComObject::CreateInstance(&pUnk); I then use thus defined pUnk in the code above which gives the following errors: Error 1 error C2065: 'm_dwRef' : undeclared identifier c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\atlcom.h 2575 Error 2 error C3861: 'FinalRelease': identifier not found c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\atlcom.h 2576 WHat would be the correct way to get pUnk? A Sample code would be highly useful. Thanks! [Edit: I'm trying to use this sample code in my IE extension application that uses ATL to handle HTMLElementEvents2. My class derives from IDispEventImpl to handle Web browser events and I'm trying to derive from another instance of IDispEventImpl to handle HTMLElementEvents2 class ATL_NO_VTABLE CMyClass: public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CSecurMailBHO, &CLSID_MyClass>, public IObjectWithSiteImpl<CMyClass>, public IDispatchImpl<ISecurMailBHO, &IID_IMyClass, &LIBID_MyClassLib, /*wMajor =*/ 1, /*wMinor =*/ 0>, public IDispEventImpl<1, CMyClass, &DIID_DWebBrowserEvents2, &LIBID_SHDocVw, 1, 1>, //Safe alternative to Invoke public IDispEventImpl<2, CMyClass, &DIID_HTMLElementEvents2, &LIBID_MSHTML, 4, 0> { . . . BEGIN_SINK_MAP(CMyClass) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_DOCUMENTCOMPLETE, OnDocumentComplete)//Do stuff OnDocumentComplete SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_BEFORENAVIGATE2, BeforeNavigate2)//Handle BeforeNavigate2 SINK_ENTRY_EX(2, DIID_HTMLElementEvents2, DISPID_HTMLELEMENTEVENTS2_ONSCROLL, OnScroll)//Handle OnScroll Event END_SINK_MAP() . . } In my OnDocumentComplete, I call IWebBrowser2::get_Document followed by IHTMLDocument2::get_body to get the IHTMLElement object body. This is what's being sent to ConnectEvents function above. But so far, no luck. I don't know what the pUnk pointer is, and further, it seems that the call to FindConnectionPoint fails, i.e, there is no HTMLElementEvents2 connection point in the point container. Any ideas as to how I should go on about handling the htmlelementevents????????? End Edit]
ATLEventHandling Sample Edit: void CMyClass::ConnectEvents(IHTMLElement* pElem) { typedef IDispEventImpl<2, CMyClass, DIID_HTMLElementEvents2, LIBID_MSHTML, 4, 0> IMyClassHTMLElementEvents2Sink; IMyClassHTMLElementEvents2Sink::DispEventAdvise(pElem); } Because you have multiple functions DispEventAdvise on the the base IDispEventImpl classes. Also it seems earliest version of MSHTML that defines HTMLElementEvents2 is 5.0.
1,127,328
1,127,344
source code of c/c++ functions
I wanted to have a look at the implementation of different C/C++ functions (like strcpy, stcmp, strstr). This will help me in knowing good coding practices in c/c++. Could you let me know where can I find it? Thanks.
You could check out a copy of glibc, which will have the source code for all C functions in the C standard library. That should be a good starting place.
1,127,350
1,127,392
difference of variable in placement of private keyword in a MFC class
Using the following code snippet as an illustration to my question: // #includes and other macros class MyClass : public CFormView { private: DECLARE_DYNCREATE(MyClass) bool privateContent; ... public: bool publicContent; ... }; class MusicPlayer { public: AppClass *theApp; // which has a pointer accessing the MyClass object instantiated in the program ... } When I place the keyword "private" in MyClass definition as such, the privateContent member variable doesn't appear to be private when I try to access it in a method of MusicPlayer class. However, if I place the "private" keyword after the DECLARE_DYNCREATE(MyClass) line, the behavior of privateContent member variable returns to what is expected. Does anyone know why this is the case? Thanks in advance.
If you look at the definition of DECLARE_DYNCREATE, you will see that it uses another macro: // not serializable, but dynamically constructable #define DECLARE_DYNCREATE(class_name) \ DECLARE_DYNAMIC(class_name) \ static CObject* PASCAL CreateObject(); And if you look at that macro, DECLARE_DYNAMIC, you'll see why your class turns public: #define DECLARE_DYNAMIC(class_name) \ protected: \ static CRuntimeClass* PASCAL _GetBaseClass(); \ public: \ static const CRuntimeClass class##class_name; \ static CRuntimeClass* PASCAL GetThisClass(); \ virtual CRuntimeClass* GetRuntimeClass() const; \ When it expands, it's going to add that public: keyword, leaving the rest of your class definition public after that. So when you say say private: after DECLARE_DYNCREATE, you're then changing it from public to private. The usual use of this macro would be like this: class MyClass : public CFormView { DECLARE_DYNCREATE(MyClass) private: bool privateContent; ... public: bool publicContent; ... }; The class will implicitly be private at the start, so the effect is the same. Also, most C++ programmers will agree you should start trying to get into the habit of placing your private variables at the bottom. The justification is that when people, including yourself, are reading the class, they will want to see what you can do with the class, which is in the public interface, rather than how the class is going to work, which is private. By putting the public interface first, you won't have to be bothered by all the private stuff. I used to put my private stuff at the top too (because I came from Visual Basic 6, before C++), and hated being told my privates should be on the bottom, but once you get into the habit you'll wish you changed sooner.
1,127,443
1,127,473
What is going on with 'function pointer' or 'reference to function' as argument to function in C++?
In Numerical Recipes they use something I've never seen done before, and couldn't easily find info on: void fun( std::vector<double> derivatives(const double, const std::vector<double> &) ) { ...; derivatives(...); ...; } Which I'm guessing is passing the function by reference (is this correct)? Why would this be favorable to using a function pointer? In which situation is each method prefered? I have a second issue: When I invoke the function for the first time the program hangs for several seconds. Now, the argument function I pass in, itself, invokes a different function from a function pointer i.e. vector<double>(*pfI)(const double) = NULL; ... pfI = pointedToFun; void argFun() { ...; deRefPointedFun = (*Theta::pfI)(t); deRefPointedFun(); } What's the better way to handle 2 levels of referenced/pointer functions?
This is equivalent to void fun( std::vector (*derivatives)(const double, const std::vector &) ) { ...; derivatives(...); ...; } And similar to how void f(int derivatives[]) { ... } is equivalent to the following void f(int *derivatives) { ... } So the parameter is a function pointer. Functions as parameters are function pointers. And arrays as parameters are pointer to their element type. It is not similar to void fun( std::vector (&derivatives)(const double, const std::vector &) ) { ...; derivatives(...); ...; } Which is a reference to a function, but only rarely used: It cannot be used for function pointer arguments, while a function pointer parameter can be used for function, function references and function pointer arguments.
1,127,460
1,127,503
How to "add reference" in C++
I'm new to C++ and there's something I just completely don't get. In C#, if I want to use an external library, log4net for example, I just add a reference to the log4net DLL and its members are automatically available to me (and in IntelliSense). How do I do that in non-managed C++?
Often, the library comes with 1) a header file (.h) and 2) a .lib file in addition to the .dll. The header file is #include'ed in your code, to give you access to the type and function declarations in the library. The .lib is linked into your application (project properties -> linker -> input, additional dependencies). The .lib file usually contains simple stubs that automatically load the dll and forward function calls to it. If you don't have a .lib file, you'll instead have to use the LoadLibrary function to dynamically load the DLL.
1,127,496
1,127,512
Namespace loop or code leak in boost::function?
I'm really baffled by this. Have I managed to do something to cause this, or is it an unclosed namespace block in boost, or some bug in VS c++ 2008? I'm definitely sure I've closed all my own namespaces properly, all includes are outside of and above them, and all my header files got include guards. alt text http://lowtown.se/stuffs/superboost.png The boost/function.hpp is only included in this header. Two other headers in my library includes the boost/cstdint.hpp but they don't have this problem.
Visual C++'s intellisense is a bit quirky. Sometimes it screws up. That doesn't mean there is a problem in your code. Always take C++ intellisense with a grain of salt.
1,127,616
1,128,702
How do I unit test a protected method in C++?
How do I unit test a protected method in C++? In Java, I'd either create the test class in the same package as the class under test or create an anonymous subclass that exposes the method I need in my test class, but neither of those methods are available to me in C++. I am testing an unmanaged C++ class using NUnit.
Assuming you mean a protected method of a publicly-accessible class: In the test code, define a derived class of the class under test (either directly, or from one of its derived classes). Add accessors for the protected members, or perform tests within your derived class . "protected" access control really isn't very scary in C++: it requires no co-operation from the base class to "crack into" it. So it's best not to introduce any "test code" into the base class, not even a friend declaration: // in realclass.h class RealClass { protected: int foo(int a) { return a+1; } }; // in test code #include "realclass.h" class Test : public RealClass { public: int wrapfoo(int a) { return foo(a); } void testfoo(int input, int expected) { assert(foo(input) == expected); } }; Test blah; assert(blah.wrapfoo(1) == 2); blah.testfoo(E_TO_THE_I_PI, 0);
1,127,617
1,127,671
What's wrong with this algorithm implementation [Sieve of Erathosthene]
I'm trying to implement the Sieve of Eratosthene in C++. However after several attempts at this I always get runtime errors. I'm thinking this has to do with the state of iterators being used get corrupted somewhere. I can't put my finger on it though. Here is my code: //Sieves all multiples of the current sequence element bool multiple_sieve(std::list<int>& num_list) { std::list<int>::iterator list_iter(num_list.begin()); std::list<int>::reverse_iterator last_element_iter(num_list.rbegin()); for(std::list<int>::iterator elements_iter(++list_iter); elements_iter != num_list.end();) { if((*elements_iter % *list_iter == 0) && (*elements_iter <= *last_element_iter) && (*list_iter != 1)) num_list.erase(elements_iter); else ++elements_iter; } return true; } std::list<int>& prime_sieve(std::list<int>& num_list) { for(std::list<int>::iterator list_iter(num_list.begin()); list_iter != num_list.end(); ++list_iter) multiple_sieve(num_list); return num_list; } What I'm doing wrong? What's generating the runtime errors? Update: When I run this in my tests I get an error with the message "list iterators are not compatible".
This line: num_list.erase(elements_iter); Is going to cause you problems since you are modifying the list while iterating it. You could do this to avoid that problem: elements_iter = num_list.erase(elements_iter); ETA: Removed stuff about erase() invalidating other iterators (looks like they are safe in this case) - just set elements_iter to the return value from erase() and you should be good to go.
1,127,738
1,127,766
cannot call member function without object
This program has the user input name/age pairs and then outputs them, using a class. Here is the code. #include "std_lib_facilities.h" class Name_pairs { public: bool test(); void read_names(); void read_ages(); void print(); private: vector<string>names; vector<double>ages; string name; double age; }; void Name_pairs::read_names() { cout << "Enter name: "; cin >> name; names.push_back(name); cout << endl; } void Name_pairs::read_ages() { cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; } void Name_pairs::print() { for(int i = 0; i < names.size() && i < ages.size(); ++i) cout << names[i] << " , " << ages[i] << endl; } bool Name_pairs::test() { int i = 0; if(ages[i] == 0 || names[i] == "0") return false; else{ ++i; return true;} } int main() { cout << "Enter names and ages. Use 0 to cancel.\n"; while(Name_pairs::test()) { Name_pairs::read_names(); Name_pairs::read_ages(); } Name_pairs::print(); keep_window_open(); } However, in int main() when I'm trying to call the functions I get "cannot call 'whatever name is' function without object." I'm guessing this is because it's looking for something like variable.test or variable.read_names. How should I go about fixing this?
You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this: int main() { Name_pairs np; cout << "Enter names and ages. Use 0 to cancel.\n"; while(np.test()) { np.read_names(); np.read_ages(); } np.print(); keep_window_open(); }
1,127,918
1,128,152
Interfaces vs Templates for dependency injection in C++
To be able to unit test my C++ code I usually pass the constructor of the class under test one or several objects that can be either "production code" or fake/mock objects (let's call these injection objects). I have done this either by Creating an interface that both the "production code" class and the fake/mock class inherits. Making the class under test a template class that takes the types of the injection objects as template parameters, and instances of the injection objects as parameters to the constructor. Some random thoughts: Until we have concepts (C++0x), only documentation and parameter naming will hint what to provide the class under test (when using templates). It is not always possible to create interfaces for legacy code The interface is basically only created to be able to do dependency injection In the same way: templating the class under test is done only to enable dependency injection What are your thoughts? Are there other solutions to this problem?
I think interface option is better, but one doesn't have to create common base class just for test. You can inherit your mock class from production class and override necessary methods. You'll have to make the methods virtual though, but that's how tools like mockpp work and they also allow automate this process a little bit.
1,127,936
1,128,006
understanding String^ in C++ .Net
I remember seeing somewhere there "^" operator is used as a pointer operator in Managed C++ code. Hence "^" should be equivalent to "*" operator right?? Assuming my understanding is right, when I started understanding .Net and coded a few example programs, I came across some code like this: String ^username; //my understanding is you are creating a pointer to string obj . . // there is no malloc or new that allocates memory to username pointer . username = "XYZ"; // shouldn't you be doing a malloc first??? isn't it null pointer I am having trouble understanding this.
String^ is a pointer to the managed heap, aka handle. Pointers and handles are not interchangable. Calling new will allocate an object on an unmanaged heap and return a pointer. On the other hand, calling gcnew will allocate an object on a managed heap and return a handle. The line username = "XYZ" is merely a compiler sugar. It is equivalent to username = gcnew String(L"XYZ");
1,128,096
1,128,259
C++ string comparison in one clock cycle
Is it possible to compare whole memory regions in a single processor cycle? More precisely is it possible to compare two strings in one processor cycle using some sort of MMX assembler instruction? Or is strcmp-implementation already based on that optimization? EDIT: Or is it possible to instruct C++ compiler to remove string duplicates, so that strings can be compared simply by their memory location? Instead of memcmp(a,b) compared by a==b (assuming that a and b are both native const char* strings).
Not really. Your typical 1-byte compare instruction takes 1 cycle. Your best bet would be to use the MMX 64-bit compare instructions( see this page for an example). However, those operate on registers, which have to be loaded from memory. The memory loads will significantly damage your time, because you'll be going out to L1 cache at best, which adds some 10x time slowdown*. If you are doing some heavy string processing, you can probably get some nifty speedup there, but again, it's going to hurt. Other people suggest pre-computing strings. Maybe that'll work for your particular app, maybe it won't. Do you have to compare strings? Can you compare numbers? Your edit suggests comparing pointers. That's a dangerous situation unless you can specifically guarantee that you won't be doing substring compares(ie, you are comparing some two byte strings: [0x40, 0x50] with [0x40, 0x42]. Those are not "equal", but a pointer compare would say they are). Have you looked at the gcc strcmp() source? I would suggest that doing that would be the ideal starting place. * Loosely speaking, if a cycle takes 1 unit, a L1 hit takes 10 units, an L2 hit takes 100 units, and an actual RAM hit takes really long.
1,128,150
1,128,453
Win32 API to enumerate dll export functions?
I found similar questions but no answer to what I am looking for. So here goes: For a native Win32 dll, is there a Win32 API to enumerate its export function names?
dumpbin /exports is pretty much what you want, but that's a developer tool, not a Win32 API. LoadLibraryEx with DONT_RESOLVE_DLL_REFERENCES is heavily cautioned against, but happens to be useful for this particular case – it does the heavy lifting of mapping the DLL into memory (but you don't actually need or want to use anything from the library), which makes it trivial for you to read the header: the module handle returned by LoadLibraryEx points right at it. #include <winnt.h> HMODULE lib = LoadLibraryEx("library.dll", NULL, DONT_RESOLVE_DLL_REFERENCES); assert(((PIMAGE_DOS_HEADER)lib)->e_magic == IMAGE_DOS_SIGNATURE); PIMAGE_NT_HEADERS header = (PIMAGE_NT_HEADERS)((BYTE *)lib + ((PIMAGE_DOS_HEADER)lib)->e_lfanew); assert(header->Signature == IMAGE_NT_SIGNATURE); assert(header->OptionalHeader.NumberOfRvaAndSizes > 0); PIMAGE_EXPORT_DIRECTORY exports = (PIMAGE_EXPORT_DIRECTORY)((BYTE *)lib + header-> OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); assert(exports->AddressOfNames != 0); BYTE** names = (BYTE**)((int)lib + exports->AddressOfNames); for (int i = 0; i < exports->NumberOfNames; i++) printf("Export: %s\n", (BYTE *)lib + (int)names[i]); Totally untested, but I think it's more or less correct. (Famous last words.)
1,128,188
1,128,208
How do I convert a LPWSTR to a GUID?
I'm working with the Windows 7 audio APIs, and I've hit a wall. Basically, I need to take an IAudioSessionControl2* and get an ISimpleAudioVolume* out of it. Now, it looks like I can call on IAudioSessionManager->GetSimpleAudioVolume() using the value of IAudioSessionControl2->GetSessionInstanceIdentifier(...). Note that this isn't exactly spelled out as such in the docs, but it seems like a reasonable behavior. The problem, GetSimpleAudioVolume() takes a GUID* and GetSessionInstanceIdentifier() spits out a LPWSTR. Through debugging I've confirmed that the return'd value from GetSessionInstanceIdentifier() at least looks like a GUID. So, the actual question is how would I convert the LPWSTR I've got into a GUID? I realise this is pretty trivial if I marshal across into some managed code and use built-in GUID, but there's got to be a C++ way of doing this. Ok, these APIs definitely do not work the way I say they do in the above text dump. However, the basic question of String -> GUID is answered so I'm not going to delete the question.
Try CLSIDFromString. A CLSID is actually defined as: typedef GUID CLSID; therefore you can use CLSIDFromString to generate a GUID. Here's some sample code: LPWSTR guidstr; GUID guid; ... HRESULT hr = CLSIDFromString(guidstr, (LPCLSID)&guid); if (hr != S_OK) { // bad GUID string... ... } Warning Things that are not GUIDs will return as valid GUIDs. For example: | String | Returned Clsid | |---------------------|----------------------------------------| | "file" | {00000303-0000-0000-C000-000000000046} | FileMoniker | "AccessControlList" | {b85ea052-9bdd-11d0-852c-00c04fd8d503} | | "ADODB.Record" | {00000560-0000-0010-8000-00AA006D2EA4} | | "m" | {4ED063C9-4A0B-4B44-A9DC-23AFF424A0D3} | Toolbar.MySearchDial This means that in addition to returning results you do not expect, the function hits the registry every time it is run. Short version: Do not use CLSIDFromString. Instead you can use IIDFromString in the exact same way.
1,128,212
1,128,243
How do you pass information from an 8 byte array into variable bit size data containers?
I have an 8 byte message where the differing chunks of the message are mapped to datums of different types (int, bool, etc.), and they vary in bit sizes (an int value is 12 bits in the message, etc.). I want to pass only the bits a datum is concerned with, but I am not sure if there is a better way. My current thoughts is to make a bit array type with a vector back end and have a templated accessor to get the value contained within to the type specified. Although as I am typing this I am starting to think a great big union of all the possible types could be passed to each datum. EDIT: The messages contain varying types of data. For example, one message contains an 8-bit int and 5 1-bit bools, while another message contains a 16-bit Timestamped (my own class) and an 8-bit int.
Are the messages alway of the same format/order? Ie. 12bitsInt|8bitsChar|etc. If so a simple solution would be to set up appropriate bitmasks to grab each particular value. Ie. if the first 12 bits (low order) corresponded to an integer we could do: __uint64 Message; // Obviously has data in it. int IntPortion = Message & 0x00000111; Which will copy the first 12 bits of the Message into the first 12 bits of your integer type. Set up appropriate bit masks for each chunk of the message and proceed. If the message format is not constant... well I would need you to elaborate maybe with an example message. Also the boost library has some nice bit manipulation classes: Dynamic Bitset Might be overkill if the format is constant though.
1,128,458
1,128,527
Memory Leak Detecting and overriding new?
I am attempting to get Memory leak detection working with the help of these two articles: http://msdn.microsoft.com/en-us/library/e5ewb1h3%28VS.80%29.aspx http://support.microsoft.com/kb/q140858/ So in my stdafx.h I now have: #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define new new(_NORMAL_BLOCK,__FILE__,__LINE__) The only problem is, I have a class which overrides the new function: class Dummy { //overloaded new operator void FAR* operator new(size_t cb); } Now when I compile this code, I get: error C2059: syntax error : 'constant' error C2091: function returns function Any idea how I can fix this?
You can use pragma directives to save and restore the new macro when undefing for overloads. See [MSDN](http://msdn.microsoft.com/en-us/library/hsttss76(VS.71).aspx) for the exact syntax. E.g. #pragma push_macro("new") #undef new void FAR* operator new(size_t cb); #pragma pop_macro("new") You can put these in headers, e.g. begin_new_override.h: #ifdef new #define NEW_WAS_DEFINED #pragma push_macro("new") #undef new #endif end_new_override.h: #ifdef NEW_WAS_DEFINED #undef NEW_WAS_DEFINED #pragma pop_macro("new") #endif And then #include "begin_new_override.h" void FAR* operator new(size_t cb); #include "end_new_override.h"
1,128,501
1,128,542
Why do implicit conversion member functions overloading work by return type, while it is not allowed for normal functions?
C++ does not allow polymorphism for methods based on their return type. However, when overloading an implicit conversion member function this seems possible. Does anyone know why? I thought operators are handled like methods internally. Edit: Here's an example: struct func { operator string() { return "1";} operator int() { return 2; } }; int main( ) { int x = func(); // calls int version string y = func(); // calls string version double d = func(); // calls int version cout << func() << endl; // calls int version }
Conversion operators are not really considered different overloads and they are not called based on their return type. The compiler will only use them when it has to (when the type is incompatible and should be converted) or when explicitly asked to use one of them with a cast operator. Semantically, what your code is doing is to declare several different type conversion operators and not overloads of a single operator.
1,128,535
1,128,598
STL vector reserve() and copy()
Greetings, I am trying to perform a copy from one vector (vec1) to another vector (vec2) using the following 2 abbreviated lines of code (full test app follows): vec2.reserve( vec1.size() ); copy(vec1.begin(), vec1.end(), vec2.begin()); While the call to vec2 sets the capacity of vector vec2, the copying of data to vec2 seems to not fill in the values from vec1 to vec2. Replacing the copy() function with calls to push_back() works as expected. What am I missing here? Thanks for your help. vectest.cpp test program followed by resulting output follows. Compiler: gcc 3.4.4 on cygwin. Nat /** * vectest.cpp */ #include <iostream> #include <vector> using namespace std; int main() { vector<int> vec1; vector<int> vec2; vec1.push_back(1); vec1.push_back(2); vec1.push_back(3); vec1.push_back(4); vec1.push_back(5); vec1.push_back(6); vec1.push_back(7); vec2.reserve( vec1.size() ); copy(vec1.begin(), vec1.end(), vec2.begin()); cout << "vec1.size() = " << vec1.size() << endl; cout << "vec1.capacity() = " << vec1.capacity() << endl; cout << "vec1: "; for( vector<int>::const_iterator iter = vec1.begin(); iter < vec1.end(); ++iter ) { cout << *iter << " "; } cout << endl; cout << "vec2.size() = " << vec2.size() << endl; cout << "vec2.capacity() = " << vec2.capacity() << endl; cout << "vec2: "; for( vector<int>::const_iterator iter = vec2.begin(); iter < vec2.end(); ++iter ) { cout << *iter << endl; } cout << endl; } output: vec1.size() = 7 vec1.capacity() = 8 vec1: 1 2 3 4 5 6 7 vec2.size() = 0 vec2.capacity() = 7 vec2:
As noted in other answers and comments, you should just use vector's built-in functionality for this. But: When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated. When you resize() the vector, it will allocate enough space for those elements, but also add them to the vector. So if you resize a vector to 100, you can access elements 0 - 99, but if you reserve 100 elements, they are not inserted yet, just ready to be used. What you want is something like this: vec2.reserve( vec1.size() ); copy(vec1.begin(), vec1.end(), std::back_inserter(vec2)); std::back_inserter is defined in <iterator>
1,128,875
1,131,234
How do I overload the << operator?
I intend to call a function whenever m_logger<<"hello"<<"world" is called. m_logger is of type ofstream. So i decide to overload << with following signature friend ofstream& operator<<(ofstream &stream,char *str); However the vc compiler gives following error: error C2666: 'operator <<' : 6 overloads have similar conversions Is there anyother way to achieve this, my objective is to divert all the write operation to ofstream object to different function? Creating an object of my own calss works for me, however how can i make it work like normal ofstream object which typecasts all system defined types into strings or char*. i know one approach would be to overload the operator for each and every type but is there a cleaner approach
The problem is that ofstream is already overloaded this way. If you make mlogger of a new type holding an ofstream, then you can do this: class mlogger_t { public: ofstream stream; ... } mlogger_t& operator<<(mlogger_t& stream, const string& str) { stream.stream << str; ... } //EDIT: here is how to make this work for other types too using templates: template<typename T> mlogger_t& operator<<(mlogger_t& stream, T val) { stream.stream << val; } ... mlogger_t mlogger; mlogger << "foo"; Also, you should definitely use a const string& (as I did in this example) rather than a C-style string. If you really need it to be C-style, at least use const char *.
1,128,929
1,129,005
Possible to break a loop when outside of it?
After trying to make a while(bool) loop and it failing because I couldn't see the contents of the vectors because there was nothing in them, I made a while(true) loop with the intention of breaking out if the user inputs a 0. Here are the important portions of the code. Edit: Working code, but what does|= mean? #include "std_lib_facilities.h" class Name_pairs { public: vector<string>names; vector<double>ages; bool test(); string read_names(); double read_ages(); void print(); }; string Name_pairs::read_names() { string name; cout << "Enter name: "; cin >> name; names.push_back(name); return name; } double Name_pairs::read_ages() { double age; cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; return age; } void Name_pairs::print() { for(int i = 0; i < (names.size()-1) && i < (ages.size()-1); ++i) cout << names[i] << " , " << ages[i] << endl; } bool Name_pairs::test() { if(ages.empty() || names.empty()) return true; if(ages.back() = 0 || names.back() == "0"){ return false;} return true; } int main() { Name_pairs np; cout << "Enter names and ages. Use 0 to cancel.\n"; bool finished = false; while(!finished){ finished |= "0" == np.read_names(); finished |= 0 == np.read_ages();} np.print(); keep_window_open(); }
If you change the problem and view it upside down it becomes quite simple. Change your setter methods to actually return the value that was just entered. I also made age a local variable of the method to prevent side effects from creeping : Double Name_pairs::read_ages() { Double age; cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; return age; } Then in the loop you can test directly for the returned value : bool finished = false; while(!finished) { finished = finished || "0" == np.read_names(); finished = finished || 0 == np.read_ages(); } Since you are setting your exit condition in the main (type 0 to exit) it is preferable to test the exit condition there for consistency. Is how I see it anyway... code is shorter and easier to understand Edit I changed the code to reflects comments aem. This way the correct logical operator is used. As for the cascading evaluation it is quite true that if the first answer was 0 then the second question will not even be asked (finished evaluated to true thus the rest of the or statement will not be evaluated) and as such you must be careful of this (if for example you expect both Vectors to always have the same length). However I found that usability wise since the user already stated that he wanted to exit I saw no use in asking him the other question.
1,128,937
1,129,964
C++ WxWidgets: Single log window for messages from Multiple Threads
What's the best/proper method to collect log messages from multiple threads and have them all be displayed using a window? (while the threads are running). I am currently trying to redirect stdout (cout) in to a wxTextCtrl but failing miserably when attempting to do so over multiple threads. Any help would be appreciated.
Logging has had a few major updates recently in the wxWidgets trunk, you can read about them here. One of them is to add support for logging from threads other than the main thread.
1,128,945
1,147,980
Get an audio session's volume level
Does anyone know how to get the current volume level of an audio session* in Vista or 7? I've got the IAudioSessionControl2 and IAudioSessionManager2 instances you need to listen for volume changes, but actually getting the current volume is proving elusive. *by audio session I mean (roughly) the per-application audio control, not the "master" one Note that (so far as I can tell) IAudioSessionManager2->GetSimpleVolume() isn't the right answer here. The only thing that publishes a GUID in IAudioSessionControl2 is the Grouping parameter, and using it in GetSimpleVolume creates new sessions rather than giving you the control for an existing one. GetSimpleVolume() is what I want, but where are the params coming from in this setup?
Actually IAudioSessionManager::GetSimpleAudioVolume IS what you're looking for. An audio session is identified by two (or three) things: The session guid, the process ID and the cross process flag (if the cross process flag is specified when the stream is created, the process ID is ignored). The simple audio volume controls the volume of all the streams within that audio session. It's fairly straightforward (most rendering frameworks specify NULL for the session GUID). If your application uses a specific session GUID, you should just specify the session GUID your application is using. There's one other twist though. The volume control (sndvol.exe) combines all sessions with the same "grouping param" together in the UI - this isn't a part of the volume control, it's a UI convenience feature that exists only for web browsers like IE - it exists to allow 3rd party audio frameworks (which specify a GUID_NULL session GUID) and the WMP OCX (which specifies a cross process session with a specific session GUID) to share a single slider in the volume UI.
1,129,012
1,129,077
How do I get IP address from socket In Windows
I have the DWORD socket in windows. I need to know if it is a connection that goes out to the internet or if it is a local connection, to some form of localhost. Is there a good way to get the address that the socket is connected to in windows from just the socket? Or is there a better way to tell if the connection is local or not?
You probably want to call getpeername(). Using it is pretty basic, you pass a sockaddr pointer and a length and it fills in the data for you. As far as determining if the connection is local, getaddrinfo() can give you a list of all available local addresses. You would compare the result of getpeername() to the local address list.
1,129,176
1,129,192
Sorting with two vectors
I'm wondering if it's possible if you have, for example, a vector<string> and a vector<double> with corresponding pairs, to sort the vector<string> alphabetically while keeping the pairs matched up. I know this can be done by creating a class that holds both values and just sorting that, but I'd rather keep two separate vectors. Any ideas? Final Code: #include "std_lib_facilities.h" struct Name_pairs { vector<string>names; vector<double>ages; void quicksort(vector<string>& num, vector<double>& num2, int top, int bottom); int divide(vector<string>& array, vector<double>& array2, int top, int bottom); bool test(); string read_names(); double read_ages(); void print(); }; string Name_pairs::read_names() { string name; cout << "Enter name: "; cin >> name; names.push_back(name); return name; } double Name_pairs::read_ages() { double age; cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; return age; } int Name_pairs::divide(vector<string>& array, vector<double>& array2, int top, int bottom) { string x = array[top]; int i = top-1; int j = bottom+1; string temp; double temp2; do{ do { j--; }while(x<array[j]); do { i++; }while(x>array[i]); if(i<j) { temp = array[i]; temp2 = array2[i]; array[i] = array[j]; array2[i] = array2[j]; array[j] = temp; array2[j] = temp2; } }while(i<j); return j; } void Name_pairs::quicksort(vector<string>& num, vector<double>& num2, int top, int bottom) // top is subscript of beginning of vector { int middle; if(top < bottom) { middle = divide(num, num2, top, bottom); quicksort(num, num2, top, middle); quicksort(num, num2, middle+1, bottom); } return; } void Name_pairs::print() { for(int i = 0; i < (names.size()-1) && i < (ages.size()-1); ++i) cout << names[i] << " , " << ages[i] << endl; } int main(){ Name_pairs np; cout << "Enter names and ages. Use 0 to cancel.\n"; bool finished = false; while(!finished){ finished = "0" == np.read_names(); finished = 0 == np.read_ages();} np.quicksort(np.names, np.ages, 0, (np.names.size()-2)); np.print(); keep_window_open();}
If you intend to use std::sort, you will need to use a datastructure like a pair. You can, of course, manually sort the vectors, and essentially reimplement std::sort. This question really depends on a great number of other questions, such as: How many items will be in the vectors? How critical is performance? Do you REALLY want to implement your own sort algorithm? Implementing a quicksort should be fairly painless, and will allow you to avoid moving the data around.
1,129,183
1,129,186
Question about inheritance
class B{ private: void DoSomething(); } class W{ private: class D: public B{ } D d; } Can I call private member function in base class of D in the scope of class W?
Nope. You can never call a private member function from anywhere except the class that owns it. If you want derived classes to be able to access it, declare it protected instead. You can also declare D to be a 'friend' of class B; that would allow D to access B.DoSomething(). However, this approach is usually frowned upon.
1,129,191
1,129,236
variable allocation in a nested loop question
because obj, the playingCard object is created inside a nested for loop does that mean after the second for loop completes, obj gets deallocated from the stack each time? and a small side question, does a compiler use the stack (similar to recursion) to keep track of loops and nested loops? for(int c = 0;c<nElems;c++) { for(int z = c + 1;z<nElems;z++) { playingCard obj; } }
It gets constructed and deconstructed every iteration. However, on the stack, the concept of allocation is (for at least VS and GCC) more hazy. Since the stack is a contiguous block of memory, premanaged by the compiler, there's no real concept of allocating and deallocating in the way that there is for heap allocations (new/delete or malloc/free). The compiler uses the memory it needs on the stack, and simply rolls back the pointer later on.
1,129,194
1,129,200
Download a URL in C++
I want to be able to download a URL in C++. Something as simple as: std::string s; s=download("http://www.example.com/myfile.html"); Ideally, this would include URLs like: ftp://example.com/myfile.dat file:///usr/home/myfile.dat https://example.com/myfile.html I was using asio in Boost, but it didn't really seem to have the code for handling protocols like ftp and https. Now I discovered QT has more what I need (http://doc.trolltech.com/2.3/network.html). It's tempting to make the switch to Qt, but it seems a bit heavy and intersects a lot of Boost functionality. Is it worth learning yet another API (Qt) or can Boost do more than I think?
Not a direct answer, but you might like to consider libCURL, which is almost exactly what you describe. There are sample applications here, and in particular this demonstrates how simple usage can be.
1,129,519
1,129,712
Fixed Length Float in C/C++?
I was wondering whether it is possible to limit the number of characters we enter in a float. I couldn't seem to find any method. I have to read in data from an external interface which sends float data of the form xx.xx. As of now I am using conversion to char and vice-versa, which is a messy work-around. Can someone suggest inputs to improve the solution?
Rounding a float (that is, binary floating-point number) to 2 decimal digits doesn't make much sense because you won't be able to round it exactly in some cases anyway, so you'll still get a small delta which will affect subsequent calculations. If you really need it to be precisely 2 places, then you need to use decimal arithmetic; for example, using IBM's decNumber++ library, which implements ISO C/C++ TR 24773 draft
1,129,710
1,129,724
User-defined cast to string in C++ (like __repr__ in Python)
How do I make something like user-defined __repr__ in Python? Let's say I have an object1 of SomeClass, let's say I have a function void function1(std::string). Is there a way to define something (function, method, ...) to make compiler cast class SomeClass to std::string upon call of function1(object1)? (I know that I can use stringstream buffer and operator <<, but I'd like to find a way without an intermediary operation like that)
Define a conversion operator: class SomeClass { public: operator std::string () const { return "SomeClassStringRepresentation"; } }; Note that this will work not only in function calls, but in any context the compiler would try to match the type with std::string - in initializations and assignments, operators, etc. So be careful with that, as it is all too easy to make the code hard to read with many implicit conversions.
1,129,894
1,130,035
Why can't you use offsetof on non-POD structures in C++?
I was researching how to get the memory offset of a member to a class in C++ and came across this on wikipedia: In C++ code, you can not use offsetof to access members of structures or classes that are not Plain Old Data Structures. I tried it out and it seems to work fine. class Foo { private: int z; int func() {cout << "this is just filler" << endl; return 0;} public: int x; int y; Foo* f; bool returnTrue() { return false; } }; int main() { cout << offsetof(Foo, x) << " " << offsetof(Foo, y) << " " << offsetof(Foo, f); return 0; } I got a few warnings, but it compiled and when run it gave reasonable output: Laptop:test alex$ ./test 4 8 12 I think I'm either misunderstanding what a POD data structure is or I'm missing some other piece of the puzzle. I don't see what the problem is.
Short answer: offsetof is a feature that is only in the C++ standard for legacy C compatibility. Therefore it is basically restricted to the stuff than can be done in C. C++ supports only what it must for C compatibility. As offsetof is basically a hack (implemented as macro) that relies on the simple memory-model supporting C, it would take a lot of freedom away from C++ compiler implementors how to organize class instance layout. The effect is that offsetof will often work (depending on source code and compiler used) in C++ even where not backed by the standard - except where it doesn't. So you should be very careful with offsetof usage in C++, especially since I do not know a single compiler that will generate a warning for non-POD use... Modern GCC and Clang will emit a warning if offsetof is used outside the standard (-Winvalid-offsetof). Edit: As you asked for example, the following might clarify the problem: #include <iostream> using namespace std; struct A { int a; }; struct B : public virtual A { int b; }; struct C : public virtual A { int c; }; struct D : public B, public C { int d; }; #define offset_d(i,f) (long(&(i)->f) - long(i)) #define offset_s(t,f) offset_d((t*)1000, f) #define dyn(inst,field) {\ cout << "Dynamic offset of " #field " in " #inst ": "; \ cout << offset_d(&i##inst, field) << endl; } #define stat(type,field) {\ cout << "Static offset of " #field " in " #type ": "; \ cout.flush(); \ cout << offset_s(type, field) << endl; } int main() { A iA; B iB; C iC; D iD; dyn(A, a); dyn(B, a); dyn(C, a); dyn(D, a); stat(A, a); stat(B, a); stat(C, a); stat(D, a); return 0; } This will crash when trying to locate the field a inside type B statically, while it works when an instance is available. This is because of the virtual inheritance, where the location of the base class is stored into a lookup table. While this is a contrived example, an implementation could use a lookup table also to find the public, protected and private sections of a class instance. Or make the lookup completely dynamic (use a hash table for fields), etc. The standard just leaves all possibilities open by restricting offsetof to POD (IOW: no way to use a hash table for POD structs... :) Just another note: I had to reimplement offsetof (here: offset_s) for this example as GCC actually errors out when I call offsetof for a field of a virtual base class.
1,130,106
1,130,112
Linking with a debug/release lib with qmake/Qt Creator
I am using Qt Creator and have a Qt GUI project that depends on a C++ static library project. I want to link the release version of the GUI app with the release build of the .lib and the debug release of the GUI app with the debug .lib. I have found out how to add additional libraries to the project by including a line like the following in my .pro file: LIBS += -L./libfolder -lmylib.lib But I cannot see how I can use a different -L command for release and debug builds. Is there support in qmake to do this?
In your project file you can do something like this debug { LIBS += -L./libfolder -lmydebuglib.lib } release { LIBS += -L./libfolder -lmyreleaselib.lib } The bit inside the debug braces is used if DEBUG has been added to the CONFIG qmake variable, similarly stuff inside the release brackets is included if RELEASE has been added to the CONFIG variable. You can also use "!debug" rather than "release" (i.e. when debug isn't in the config) You can find more information on qmake here.
1,130,360
1,130,408
Checking digital signature programmatically
I have the exe for the project im working on signed by a digital signature which means when it asks for admin rights it shows the company name. This works very well but if you modify the exe it will still work and show unknown there instead. Is there a way to check the digital signature to see if it is valid when you run the exe to avoid modified versions running? Visual studio 2008 windows 7
Here is a sample program(it uses WinVerifyTrust function) that verifies signature, but I'm not sure that it will work under Windows 7. You should try it.
1,130,440
1,130,452
Is it possible to assign object to int?
I have a CCounter class which holds and integer value protected by mutex. I've defined several operators like post/pre inc/dec returning an integer so I can do: CCounter c(10); int i = c++; but what do I do with a simple assignment like i = c ? I tried to define friend operator= but it gives me operator=(int&, const CCounter&)’ must be a nonstatic member function error. Please, advise. Thanks.
You need to define a casting operator that casts from CCounter to int. Add this member to your class: operator int() const { return ...; }
1,130,761
14,085,970
compile cdrtools with mingw
I need to compile cdrtools with mingw (to avoid cygwin dependancy). It was done somehow long time ago but sources are not available anymore: http://web.archive.org/web/20040707140819/http://cdrtools.bootcd.ru/ Does anyone know how to compile cdrtools with mingw? Thanks.
These so called "forks" both have less functionality than the original software but they are full of bugs and dead since many years. dvdrtools started with a cdrtools version from 2001 (now 12 years old), removed the original DVD support code and replaced that by something that may work with a Pioneer A03. It did not destroy portability so it compiles on Win-DOS as cdrtools from 2001 do. wodim uses a cdrtools version from September 2004 and did the same for the dvd support code but in addition destroyed the portability framework and added own specific bugs. Cdrtools compile and work on Win-Dos since aprox. y1998. To compile on Win-Dos, you need a cygwin environment and "smake" (gmake has bugs that prevent it from working correctly on that platform). On such an environment, you may compile for cygwin and even using cl.exe. If you use cl.exe to compile, you will not get a working mkisofs due to intended non-POSIX compliance of the compile enviroment from Microsoft (struct stat always contains st_ino == 0, telling mkisofs that all files are hardlinked together). There was a working mingw compile several years ago, but it seems that the instructions in READMEs/README.mingw32 no longer apply. There has been a DJGPP compile aprox. 10 years ago (see READMEs/README.msdos) but this is also no longer correct for current DJGPP releases.
1,130,906
1,130,918
Can I add breakpoint on CreateProcess in VS
Can I add breakpoint on windows CreateProcess API in Visual studio like I can do in Windbg?
Yes - Go "Debug / New breakpoint / Break at function..." and paste this: {,,kernel32.dll}_CreateProcessW@40 into the Function box. That assumes a Unicode build - replace W with A for ANSI builds. A bit of explanation: the @40 piece is part of the stdcall calling convention, and gives the number of bytes of parameters that the function takes. In win32, this is almost always 4 times the number of parameters. The underscore is also part of the stdcall calling convention. A related note: sometimes the name of the function as seen by the debugger is different from its real name - see this blog post for an example, and how to find the right name to use: Setting a Visual Studio breakpoint on a Win32 API function in user32.dll
1,131,064
1,131,250
Transfer a boost::ptr_list from a library to a client
I dynamically load a library in C++ like described here. My abstract base class looks like this: #include <boost/ptr_container/ptr_list.hpp> class Base { public: virtual void get_list(boost::ptr_list<AnotherObject>& list) const = 0; }; And my library now provides a derived class Derived class Derived : public Base { ... }; void Derived::get_list(boost::ptr_list<AnotherObject& list) const { list.push_back(new AnotherObject(1)); list.push_back(new AnotherObject(2)); } and create and destroy functions extern "C" { Base* create() { new Derived; } destroy(Base* p) { delete p; } } My client program loads the library and the two create and destroy functions. Then it creates an instance of Derived and uses it: Base* obj = create(); boost::ptr_list<AnotherObject> list; obj->get_list(list); Now my problem: When the list is filled by the library the library's new is called to create the AnotherObjects. On the other hand when the list is destroyed the client's delete is called for destroying the AnotherObjects. What can I do to avoid this problem?
Use a std::list<shared_ptr<AnotherObject> >. Pass a custom deleter to the shared_ptr that calls the proper delete.
1,131,221
1,131,247
Link Checker With ShellExecute?
I've been tasked with going through a database and checking all of the links, on a weekly schedule. I normally work in PHP, but doing this in PHP would be very slow (it actually would timeout the page after about 100 URLs), so I decided to make a quick C++ app. Admitidly, I haven't used C++ since college, so I'm a bit rusty. I found the ShellExecute function, and that it would open the page no problem. Here is what I have so far: #include <shlobj.h> #include <iostream> using namespace std; int main() { if( ShellExecute(NULL,"find","http://example.com/fdafdafda.php",NULL,NULL,SW_SHOWDEFAULT) ) { cout << "Yes"; } else { cout << "No"; } cout << endl; system("PAUSE"); return 0; } The problem is that it always returns true, whether it is opening a valid page or not. It appears to be checking if the associated app (a browser in this case) is able to open the document with no problems, then returns true. It isn't looking to see if the browser is getting a 404 or not, it simply sees it open and run and is fine. Is there a better way to do this? Am I missing a step? As an aside, I have attempted to use the cURLcpp stuff, but can't seem to figure it out. All of the examples point to header files that don't exist in the download. I have a feeling cURLcpp is the better way to do this. Thanks for any help.
I think you answered your own question. ShellExecute is really not appropriate for this task, and something like CURL would be better.
1,131,582
1,131,597
Error while using Boost with Visual Studio 2008
I am using Boost with Visual Studio 2008 and I have put the path to boost directory in configuration for the project in C++/General/"Additional Include Directories" and in Linker/General/"Additional Library Directories". (as it says here: http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#build-from-the-visual-studio-ide) When I build my program, I get an error: fatal error C1083: Cannot open include file: 'boost/python.hpp': No such file or directory I have checked if the file exists, and it is on the path. I would be grateful if anyone can solve this problem. The boost include path is C:\Program Files\boost\boost_1_36_0\boost. Linker path is C:\Program Files\boost\boost_1_36_0\lib. The file python.hpp exists on the include path.
Where is the file located, and which include path did you specify? (And how is the file #include'd) There's a mismatch between some of these But it's impossible to say what's wrong when you haven't shown what you actually did. Edit: Given the paths you mentioned in comments, the problem is that they don't add up. If the include path is C:\Program Files\boost\boost_1_36_0\boost, and you then try to include 'boost/python.hpp", the compiler searches for this file in the include path, which means it looks for C:\Program Files\boost\boost_1_36_0\boost\boost\python.hpp, which doesn't exist. The include path should be set to C:\Program Files\boost\boost_1_36_0 instead.
1,131,639
1,132,514
How are float and doubles represented in C++ (gcc)?
How are floating points represented and interpreted by a compiler. I am trying to understand that so I can easily interpret what byte array would mean for floats and doubles. Thanks
To actually interpret it you would probably not want to treat it as bytes anyway because mantisa boundries don't align to an 8bit boundry. Something along the lines of: mantisa = (*(unsigned int *)&floatVal) | MANTISA_MASK; exp = ((*(unsigned int *)&floatVal) | EXP_MASK ) >> EXP_SHIFT; sign = ((*(unsigned int *)&floatVal) | SIGN_MASK ) >> SIGN_SHIFT; Would let you pull it apart to play with the juice center. EDIT: #include <stdio.h> void main() { float a = 4; unsigned int exp,sign,mantisa; int i; for(i = 0;i<4;i++) { exp = (*((unsigned int *)&a) >>23) & 0xFF; sign = (*((unsigned int *)&a) >>31) & 0x01; mantisa = (*((unsigned int *)&a)) & 0x7FFFFF | 0x800000; printf("a = %04x\r\n",*((unsigned int *)&a)); printf("a = %f\r\n",a); printf("exp = %i, %02x\r\n",exp,exp); printf("sign = %i, %02x\r\n",sign,sign); printf("mantisa = %i, %02x\r\n\r\n",mantisa,mantisa); a = -a / 2; } } Produces: a = 40800000 a = 4.000000 exp = 129, 81 sign = 0, 00 mantisa = 8388608, 800000 a = c0000000 a = -2.000000 exp = 128, 80 sign = 1, 01 mantisa = 8388608, 800000 a = 3f800000 a = 1.000000 exp = 127, 7f sign = 0, 00 mantisa = 8388608, 800000 a = bf000000 a = -0.500000 exp = 126, 7e sign = 1, 01 mantisa = 8388608, 800000 Press any key to continue . . .
1,132,175
1,132,396
Custom sorting, always force 0 to back of ascending order?
Premise This problem has a known solution (shown below actually), I'm just wondering if anyone has a more elegant algorithm or any other ideas/suggestions on how to make this more readable, efficient, or robust. Background I have a list of sports competitions that I need to sort in an array. Due to the nature of this array's population, 95% of the time the list will be pre sorted, so I use an improved bubble sort algorithm to sort it (since it approaches O(n) with nearly sorted lists). The bubble sort has a helper function called CompareCompetitions that compares two competitions and returns >0 if comp1 is greater, <0 if comp2 is greater, 0 if the two are equal. The competitions are compared first by a priority field, then by game start time, and then by Home Team Name. The priority field is the trick to this problem. It is an int that holds a positve value or 0. They are sorted with 1 being first, 2 being second, and so on with the exception that 0 or invalid values are always last. e.g. the list of priorities 0, 0, 0, 2, 3, 1, 3, 0 would be sorted as 1, 2, 3, 3, 0, 0, 0, 0 The other little quirk, and this is important to the question, is that 95% of the time, priority will be it's default 0, because it is only changed if the user wants to manually change the sort order, which is rarely. So the most frequent case in the compare function is that priorities are equal and 0. The Code This is my existing compare algorithm. int CompareCompetitions(const SWI_COMPETITION &comp1,const SWI_COMPETITION &comp2) { if(comp1.nPriority == comp2.nPriority) { //Priorities equal //Compare start time int ret = comp1.sStartTime24Hrs.CompareNoCase(comp2.sStartTime24Hrs); if(ret != 0) { return ret; //return compare result }else { //Equal so far //Compare Home team Name ret = comp1.sHLongName.CompareNoCase(comp2.sHLongName); return ret;//Home team name is last field to sort by, return that value } } else if(comp1.nPriority > comp2.nPriority) { if(comp2.nPriority <= 0) return -1; else return 1;//comp1 has lower priority }else /*(comp1.nPriority < comp2.nPriority)*/ { if(comp1.nPriority <= 0) return 1; else return -1;//comp1 one has higher priority } } Question How can this algorithm be improved? And more importantly... Is there a better way to force 0 to the back of the sort order? I want to emphasize that this code seems to work just fine, but I am wondering if there is a more elegant or efficient algorithm that anyone can suggest. Remember that nPriority will almost always be 0, and the competitions will usually sort by start time or home team name, but priority must always override the other two.
Isn't it just this? if (a==b) return other_data_compare(a, b); if (a==0) return 1; if (b==0) return -1; return a - b;
1,132,453
1,132,965
Is there a way to prevent a "keyword" from being syntax highlited in MS Visual Studio
MS Visual Studio editor highlights some non-keyword identifiers as keywords in C++ files. Particularly "event" and "array" are treated as keywords. That's very annoying to me, because they are not C++ keywords. I know how to add my own keywords to the list of syntax-highlighted identifiers, but how to remove existing built-in ones? I'm aware that this may require patching some executable files. So does anyone know how to do this?
It doesn't look like a disable-syntax-coloring feature is exposed in a user-friendly way. The only way I can think of selectively disabling syntax coloring is to create a new syntax coloring plugin for the IDE, and list all of the keywords you want colored. Microsoft gives information in this article on how to accomplish this task. The drawback to this approach is that your IDE will now have two C++ languages and I'm not sure how it will select which plug-in to choose from once it loads a .h or .cpp file. However, this article suggests that you can override the existing C++ plug-ins by rewriting some registry keys.
1,132,924
1,132,962
What aspect oriented language is a good place to start for a c++ programmer
The only one I know of is called "e" which is used for test bench design in hardware design and verification but I want something for general purpose programming.
Aspect oriented programming isn't so much a defining feature of a language, it's a paradigm that can be applied to many existing programming languages. You'd be hard-pressed to find a specific language that's aspect oriented in nature, though one could exist that makes adding cross-cutting concerns easy out of the box. Starting with Wikipedia's entry on Aspect-oriented programming should point you to several implementations specifically for C++.
1,132,951
1,132,994
Specialize member function template of a class template
I have the following code: #include <stdio.h> template<int A> class Thing { // 5 public: Thing() : data(A) { } template<int B> Thing &operator=(const Thing<B> &other) { printf("operator=: A = %d; B = %d\n", A, B); printf("this->data = %d\n", data); } private: int data; }; int main() { Thing<0> a, b; Thing<1> c; a = b; a = c; c = b; return 0; } I need to specialize Thing<A>::operator= for A == B. I have tried this: template<int B> template<int A> Thing<A> &Thing<A>::template operator=(const Thing<A> &other) { // 23 printf("operator= (specialized): A = %d; B = %d; A %c= B\n", A, B, (A == B) ? '=' : '!'); printf("this->data = %d; other.data = %d\n", data, other.data); } However, I receive compile errors with g++: 23: error: invalid use of incomplete type ‘class Thing<B>’ 5: error: declaration of ‘class Thing<B>’ I have tried using an if(A == B) in operator= without a specialization. However, I receive errors for accessing the private member data, which I need to access where A == B. How can I properly specialize my member function template operator= of the class template Thing?
I don't think you need to specialize it, can't you just provide an overload for operator=? template<int A> class Thing { // 5 public: Thing() : data(A) { } template<int B> Thing &operator=(const Thing<B> &other) { printf("operator=: A = %d; B = %d\n", A, B); printf("this->data = %d\n", data); } Thing &operator=(const Thing &other) { printf("operator overload called"); printf("this->data = %d\n", data); } private: int data; }; IIRC there are some lookup gotchas if you try to combine overloads with specializations, but that doesn't look necessary here.
1,132,987
1,133,258
C++ interacting with a dynamic webpage?
I was thinking recently about what projects I could start that would be of use to me and this came up. I post on various forums a daily updated journal entry that is the same for each forum. I also keep a log of the journal entries as individual docx files on my hard drive. I figured it would be great if I could create a program that would be given an input docx file and then post its contents as a new reply to all the daily journal threads on the forums that I have. I am well versed in c++ for college like programming (algorithms, programming competitions, science based assignments and such), but not at all experienced with practical applications. My first question to get me started with this new idea of mine is if there are any libraries for c++ that allow for an interaction to a dynamic webpage like I described. Thanks Much, Michael
That problem can be approached as simply as using cURL (or a similar library) to GET pages and POST form data, or it could be as complicated as writing a Firefox XPCOM extension.
1,133,170
1,133,223
array of integers vs. pointer to integer in c++
If I have int x[10] and int *y, how can I tell the difference between the two? I have two ideas: sizeof() is different. &x has different type --- int (*p)[10] = &x works but not int **q = &x. Any others? In some template library code, I need to determine whether a pointer is a "real" pointer or degenerated from an array. I can't look at source code as the library user does not exist until I write the library. ... I can work around this by rewriting the code, so now this is only a theoretical exercise.
The sizeof idea is not very good, because if the array happens to have a single element, and the element type happens to be the same size as a pointer, then it will be the same size as the size of a pointer. The type matching approach looks more promising, and could presumably be used to pick a template specialization (if that's what you're up to).
1,133,534
1,133,921
#import'ing msado15.dll, is there another way?
In all ADO C++ code I can find, there is a line #import "C:\Program Files\Common Files\System\ADO\msado15.dll" no_namespace rename("EOF", "EndOfFile") I understand that this line "incorporate information from a type library", and that "The content of the type library is converted into C++ classes". What? I'm also looking for the header file for ADO C++, but I can't seem to find it.
It's been a while since I played with that stuff, so what follows is a bit vague and may even be slightly inaccurate, but I hope it still helps: The DLL implements COM interfaces, and contains a type library describing those interfaces. Among other things, a type library contains the IDL of those interfaces, which should be compiled to generate C++ header files that your program can use. The #import directive automates the process of extracting the TLB from the DLL and compiling the interfaces it describes to generate the corresponding C++ headers, and #include-ing the generated headers.
1,133,598
1,133,646
Qt and C++ - undefined reference to slot
I have a build error with a slot in Qt. I have an class which has a public slot: void doSomething(); In constructor of this class i do: this->connect( ui->textFrom, SIGNAL(returnPressed()), this, SLOT(doSomething()) ); I have QLineEdit - textFrom object. The build error is ../moc_mainwindow.cpp:66: undefined reference to `MainWindow::doSomething()' :-1: error: collect2: ld returned 1 exit status Help me, please (:
void doSomething(); looks like a snip from the header file, did you implement the slot itself?
1,133,722
1,134,095
Things to keep in mind when migrating from VS2008 to VS2010
So, I'll be soon working on porting two APIs (C++ and C++/CLI) to use the VS2010 compiler. I think it'd be a good idea to have a head start on this. Any tips?
Breaking changes to C++/STL projects are outlined here. vs2010 will also use a different build mechanism in the for of MSBuild. Unfortunately, the revamped Intellisense in vs2010 won't extend to C++/CLI which some people aren't too happy about, however native code developer can look forward to a more responsive environment (hopefully).
1,133,739
1,134,501
how does ofstream or ostream type cast all types to string?
any system defined user type past to ostream object is converted to a string or char* ? like cout<<4<<"Hello World"; works perfectly fine, how is this achieved? is the << operator overloaded for each and every type? is there a way to achieve it through just one generic overloaded function? what i mean is can i have just one overloaded operator method with one parameter(like void*) and then decide inside that method how to typecast integer to char* Things worked partially if i overload operator << using Template i.e class UIStream { private: ofstream stream; public: UIStream(); ~UIStream(); template <typename T> UIStream& operator << (const T); }; so this works UIStream my_stream; my_stream<<"bcd"<10; however it gives compiler error when i do this my_stream <<endl; error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'UIStream' (or there is no acceptable conversion) Is not std::endl a type of object too?
After re-reading your question (as a result of a comment in this answer) I have realized that what you want is not only conversions into string (my assumptions in the other answer here), but rather forwarding into the internal ofstream. Now, what you want to achieve is not simple, and may be overkill in most cases. In the implementation of [make_string][3] that I have (that forwards to an internal ostringstream), I don't allow for manipulators to be passed. If the user wants to add a new line (we develop under linux) they just pass a '\n' character. Your problem is forwarding manipulators (std::hex, std::endl...). Your operator<< is defined as taking a constant instance of a type T, but manipulators are function pointers and the compiler is not able to match it against your methods. Manipulators are functions that operate on the std::basic_ostream template. The basic_ostream template and ostream class are defined as: template <typename TChar, typename TTraits = char_traits<TChar> > class basic_ostream; typedef basic_ostream<char> ostream; // or // typedef basic_ostream<wchar_t> if using wide characters Then the possible manipulators that can be passed to a std::ostream are: typedef std::ostream& (*manip1)( std::ostream& ); typedef std::basic_ios< std::ostream::char_type, std::ostream::traits_type > ios_type; typedef ios_type& (*manip2)( ios_type& ); typedef std::ios_base& (*manip3)( std::ios_base& ); If you want to accept manipulators you must provide that overload in your class: class mystream { //... public: template <typename T> mystream& operator<<( T datum ) { stream << datum; return *this } // overload for manipulators mystream& operator<<( manip1 fp ) { stream << fp; return *this; } mystream& operator<<( manip2 fp ) { stream << fp; return *this; } mystream& operator<<( manip3 fp ) { stream << fp; return *this; } }; In particular, the signature for endl (which may be the only one you require) is: template <typename Char, typename Traits> std::basic_ostream<Char,Traits>& std::endl( std::basic_ostream<Char,Traits>& stream ); so it falls under the manip1 type of functions. Others, like std::hex fall under different categories (manip3 in this particular case)
1,133,902
1,133,917
How can/should C++ static member variable and function be hidden?
m_MAX and ask() are used by run() but should otherwise not be public. How can/should this be done? #include <vector> class Q { public: static int const m_MAX=17; int ask(){return 4;} }; class UI { private: std::vector<Q*> m_list; public: void add(Q* a_q){m_list.push_back(a_q);} int run(){return Q::m_MAX==m_list[0]->ask();} }; int main() { UI ui; ui.add(new Q); ui.add(new Q); int status = ui.run(); }
You could define both m_MAX and ask() within the private section of class Q. Then in Q add: "friend class UI". This will allow UI to access the private members of Q, but no one else. Also note that UI must be defined before the "friend class UI" statement. A forward declaration will work.
1,133,955
1,134,007
Why would a virtual function be private?
I just spotted this in some code: class Foo { [...] private: virtual void Bar() = 0; [...] } Does this have any purpose? (I am trying to port some code from VS to G++, and this caught my attention)
See this Herb Sutter article as to why you'd want to do such a thing.
1,134,006
1,134,061
real use cases of casting operators
I want to know more about the casting (like static cast, dynamic cast, const cast and reinterpret cast) and when do we REALLY need that (real life scenario)? Any references/links/books will be appreciated. Thanks.
This article will do.
1,134,050
1,480,101
Is there a way to preserve the BITMAPFILEHEADER when loading a Bitmap as a Windows resource?
I've been working on testing a few things out using SFML 1.4 (Simple and Fast Multimedia Library) with C++ and Visual C++ 2008 Express Edition. To avoid having external images with my graphical programs, I was testing out the sf::Image::LoadFromMemory(const char * Data, std::size_t SizeInBytes) function with Bitmap resources loaded using a simple resource script: IDB_SPRITE BITMAP "sprite1.bmp" In my code to load the image to create an sf::Image using this bitmap resource, I use the following procedure, consisting of Win32 API functions (I've excluded the code that checks to make sure the Win32 functions don't return NULL to shorten this a bit): HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(IDB_SPRITE), RT_BITMAP); HGLOBAL hResData = LoadResource(NULL, hResInfo); char * resourceData = reinterpret_cast<char *>(LockResource(hResData)); After that, I use the sf::Image::LoadFromMemory function: MyImage.LoadFromMemory(resourceData, SizeofResource(NULL, hResInfo)); However, this doesn't work (I get an unknown file type error). After some testing, I discovered that the bitmap data I pass to the LoadFromMemory function does not include the BITMAPFILEHEADER (the first 14 bytes), and I believe this is the cause of the unknown file type error. I can restore the BITMAPFILEHEADER manually and get the LoadFromMemory function to work fine. However, I'm wondering if there is some way to preserve the BITMAPFILEHEADER in the resource data to avoid doing this?
Using a custom resource type will preserve the entire file. Change the resource script to utilize the RCDATA type as opposed to the BITMAP type: IDB_SPRITE RCDATA "sprite1.bmp" In the FindResource function call, use RT_RCDATA instead of RT_BITMAP: HRSRC hResInfo = FindResource(NULL, MAKEINTRESOURCE(IDB_SPRITE), RT_RCDATA); For more information: RCDATA Resource Resource Types
1,134,237
1,134,271
Pedantic gcc warning: type qualifiers on function return type
When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the -Wall -Wextra options) I suddenly got a bunch of errors of the form warning: type qualifiers ignored on function return type. Consider temp.cpp: class Something { public: const int getConstThing() const { return _cMyInt; } const int getNonconstThing() const { return _myInt; } const int& getConstReference() const { return _myInt; } int& getNonconstReference() { return _myInt; } void setInt(const int newValue) { _myInt = newValue; } Something() : _cMyInt( 3 ) { _myInt = 2; } private: const int _cMyInt; int _myInt; }; Running g++ temp.cpp -Wextra -c -o blah.o: temp.cpp:4: warning: type qualifiers ignored on function return type temp.cpp:7: warning: type qualifiers ignored on function return type Can someone tell me what I am doing wrong that violates the C++ standard? I suppose that when returning by value, the leading const is superfluous, but I'm having trouble understanding why it's necessary to generate a warning with it. Are there other places where I should leave off the const?
It doesn't violate the standard. That's why they're warnings and not errors. And indeed you're right — the leading const is superfluous. The compiler warns you because you've added code that in other circumstances might mean something, but in this circumstance means nothing, and it wants to make sure you won't be disappointed later when your return values turn out to be modifiable after all.
1,134,388
1,134,467
std::endl is of unknown type when overloading operator<<
I overloaded operator << template <Typename T> UIStream& operator<<(const T); UIStream my_stream; my_stream << 10 << " heads"; Works but: my_stream << endl; Gives compilation error: error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'UIStream' (or there is no acceptable conversion) What is the work around for making my_stream << endl work?
std::endl is a function and std::cout utilizes it by implementing operator<< to take a function pointer with the same signature as std::endl. In there, it calls the function, and forwards the return value. Here is a code example: #include <iostream> struct MyStream { template <typename T> MyStream& operator<<(const T& x) { std::cout << x; return *this; } // function that takes a custom stream, and returns it typedef MyStream& (*MyStreamManipulator)(MyStream&); // take in a function with the custom signature MyStream& operator<<(MyStreamManipulator manip) { // call the function, and return it's value return manip(*this); } // define the custom endl for this stream. // note how it matches the `MyStreamManipulator` // function signature static MyStream& endl(MyStream& stream) { // print a new line std::cout << std::endl; // do other stuff with the stream // std::cout, for example, will flush the stream stream << "Called MyStream::endl!" << std::endl; return stream; } // this is the type of std::cout typedef std::basic_ostream<char, std::char_traits<char> > CoutType; // this is the function signature of std::endl typedef CoutType& (*StandardEndLine)(CoutType&); // define an operator<< to take in std::endl MyStream& operator<<(StandardEndLine manip) { // call the function, but we cannot return it's value manip(std::cout); return *this; } }; int main(void) { MyStream stream; stream << 10 << " faces."; stream << MyStream::endl; stream << std::endl; return 0; } Hopefully this gives you a better idea of how these things work.
1,134,658
1,134,765
Sockets: How to send data to the client without 'waiting' on them as they receive/parse it
I have a socket server, written in C++ using boost::asio, and I'm sending data to a client. The server sends the data out in chunks, and the client parses each chunk as it receives it. Both are pretty much single threaded right now. What design should I use on the server to ensure that the server is just writing out the data as fast as it can and never waiting on the client to parse it? I imagine I need to do something asynchronous on the server. I imagine changes could be made on the client to accomplish this too, but ideally the server should not wait on the client regardless of how the client is written. I'm writing data to the socket like this: size_t bytesWritten = m_Socket.Write( boost::asio::buffer(buffer, bufferSize)); Update: I am going to try using Boost's mechanism to write asynchronously to the socket. See http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/tutorial/tutdaytime3/src.html e.g. boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); Alex
If you set your socket to non-blocking, then writes should fail if they would otherwise block. You can then queue up the data however you like, and arrange for another attempt to be made later to write it. I don't know how to set socket options in the boost socket API, but that's what you're looking for. But this is probably more trouble than it's worth. You'd need to select a socket that's ready for writing, presumably from several open simultaneously, shove more data into it until it's full, and repeat. I don't know if the boost sockets API has an equivalent of select, so that you can wait on multiple sockets at once until any of them is ready to write. The reason that servers typically start a thread (or spawn a process) per client connection is precisely so that they can get on with serving other clients while they're waiting on I/O, while avoiding implementing their own queues. The simplest way to "arrange for another attempt later" is just to do blocking I/O in a dedicated thread. What you can't do, unless boost has done something unusual in its sockets API, is require the OS or the sockets library to queue up arbitrary amounts of data for you without blocking. There may be an async API which will call you back when the data is written.
1,134,931
1,134,949
Reading/Understanding third-party code
When you get a third-party library (c, c++), open-source (LGPL say), that does not have good documentation, what is the best way to go about understanding it to be able to integrate into your application? The library usually has some example programs and I end up walking through the code using gdb. Any other suggestions/best-practicies? For an example, I just picked one from sourceforge.net, but it's just a broad engineering/programming question: http://sourceforge.net/projects/aftp/
I frequently use a couple of tools to help me with this: GNU Global. It generates cross-referencing databases and can produce hyperlinked HTML from source code. Clicking function calls will take you to their definitions, and you can see lists of all references to a function. Only works for C and perhaps C++. Doxygen. It generates documentation from Javadoc-style comments. If you tell it to generate documentation for undocumented methods, it will give you nice summaries. It can also produce hyperlinked source code listings (and can link into the listings provided by htags). These two tools, along with just reading code in Emacs and doing some searches with recursive grep, are how I do most of my source reverse-engineering.
1,135,018
1,135,039
Achieving Interface functionality in C++
A big reason why I use OOP is to create code that is easily reusable. For that purpose Java style interfaces are perfect. However, when dealing with C++ I really can't achieve any sort of functionality like interfaces... at least not with ease. I know about pure virtual base classes, but what really ticks me off is that they force me into really awkward code with pointers. E.g. map<int, Node*> nodes; (where Node is the virtual base class). This is sometimes ok, but sometimes pointers to base classes are just not a possible solution. E.g. if you want to return an object packaged as an interface you would have to return a base-class-casted pointer to the object.. but that object is on the stack and won't be there after the pointer is returned. Of course you could start using the heap extensively to avoid this but that's adding so much more work than there should be (avoiding memory leaks). Is there any way to achieve interface-like functionality in C++ without have to awkwardly deal with pointers and the heap?? (Honestly for all that trouble and awkardness id rather just stick with C.)
Template MetaProgramming is a pretty cool thing. The basic idea? "Compile time polymorphism and implicit interfaces", Effective C++. Basically you can get the interfaces you want via templated classes. A VERY simple example: template <class T> bool foo( const T& _object ) { if ( _object != _someStupidObject && _object > 0 ) return true; return false; } So in the above code what can we say about the object T? Well it must be compatible with '_someStupidObject' OR it must be convertible to a type which is compatible. It must be comparable with an integral value, or again convertible to a type which is. So we have now defined an interface for the class T. The book "Effective C++" offers a much better and more detailed explanation. Hopefully the above code gives you some idea of the "interface" capability of templates. Also have a look at pretty much any of the boost libraries they are almost all chalk full of templatization.
1,135,187
1,135,217
Porting to Solaris SPARC using Sun Studio 12
I am trying to compile an object file using the code below. //--Begin test.cpp class A; void (A::* f_ptr) (); void test() { A *a; (a->*f_ptr)(); } //-- End test.cpp For GNU g++ compiler, it is able to compile the object file. $ g++ -c test.cpp But for Sun Studio 12 on a Solaris 10 (SPARC), it outputs an error. $ CC -c test.cpp "test.cpp", line 7: Error: Cannot call through pointer to member function before defining class A. 1 Error(s) detected. Is there a compiler flags to get the Sun Studio C++ compiler to build the object file? Is there another workaround?
Try to #include <A.h> in that file. The compiler needs to know what class A looks like.
1,135,392
1,141,445
serial communication anomaly in Linux?
I am using select call to communicate with an external subsystem (protocol for the same has been provided and implemented as a Qt thread) using serial port RS232. We do not have the hardware for the external systems and thus we have developed in house simulators using .Net 2.0 and C# to mimic the behavior of the underlying subsystem hardware. There are 5 different subsystem that communicate with our application. Every interface for the subsystem is implemented as a Qt thread. Since this isn't a real time application, and we do not have the actual hardware when we communicate using simulators, all systems do find for 24 hrs or so and after that the communication goes up and down and ultimately all communication breaks down, but when I restart the simulator machine without closing my application, things become alright. Why does this happen? My guess is, since .Net/C# isn't a real time framework and also after the simulators have run for 24 hrs, the data sending rates start to slow down, that there is clogging of serial ports; the restart flushes everything and thus everything returns to normal. This is just a guess. If someone has a better opinion, do share it. Note, the simulators have been made by a different team of .Net guys. Note: Each protocol has different data rates, 1 Hz, 5 Hz, 10 Hz. There is one system which just doesn't resume communication even after simulator for the same is restarted after reboot. The port configuration for this system is SetPortConfiguration() { tcgetattr(Fd,&mOldtio); mNewtio.c_cflag = B4800 | CS8 | CLOCAL | CREAD | CRTSCTS; mNewtio.c_iflag = 0; //setting the input flag to icrnl causes a blank frame to be displayed after every frame. mNewtio.c_oflag = 0; mNewtio.c_lflag =ICANON; mNewtio.c_cflag &=~PARENB; mNewtio.c_cflag &= ~CSTOPB; //mNewtio.c_cflag &= ~HUPCL; //added on 24/3/09 mNewtio.c_cc[VEOL]=0; //setting VEOL to '\r' or '\n' causes a blank frame to be displayed after every frame. mNewtio.c_cc[VKILL] = 0; /* @ */ mNewtio.c_cc[VSTART] = 0; /* Ctrl-q */ mNewtio.c_cc[VSTOP] = 0; /* Ctrl-s */ mNewtio.c_cc[VMIN]=0; mNewtio.c_cc[VTIME]=0; tcflush(Fd, TCIFLUSH); tcflow(Fd,TCION); tcsetattr(Fd,TCSANOW,&mNewtio); } Also there is a reset port function : ResetPort() { tcflush(Fd, TCIFLUSH); //flush all data received but not read tcflow(Fd,TCIOFF); //transmits a STOP character, which stops the terminal device from transmitting data to the system tcsetattr(Fd, TCSANOW, &mOldtio);//set the old terminal settings ClosePort(); //close port OpenPort(mStrPortNo); //open the port specified by port number and in read mode SetPortConfiguration(); } If there is any break in communication, I call the ResetPort function which closes and reopens the port. This solves the problem in all cases except one system say XYZ. XYZ system sends data in NMEA format with each packet as a string of data terminated with a Carriage Return, LineFeed combination. Any idea fellows as to what may be the problem?
I have solved the problem. My apologies if I couldn't get across my point. Earlier we were using signal handling for serial interfacing with each system connected to a dedicated serial port, this design was flawed from start as signal handler in our case was way too complex. Ideally a signal handler should just set some flags, it shouldn't involve function calls as there can be synchronisation issues to be handled, then it snowballs into a synchronisation nightmare which is hard to debug as I found out in my application. This design leads to loss in packets coming from the serial ports. To deal with this situation we were using reset port function which was a crude way to rectify the packet loss problem. I dropped the signal handler and used select call for individual systems. But didn't drop reset port which was a part of earlier design. On debugging, I found resetport a spurious function and dropped it. Voila!! everything works perfect now. On record, my advice to anyone who is using serial communication on a linux paltform to use select system call. You are absolved of handling the details of serial communication and just concentrate on processing the incoming packets. I hope this solution will help all those who are working on serial communication on linux/unix platforms. There isn't much literature on the subject and all search on the net will lead you to some documents by mike and sweet which though good aren't much help in practical applications. I acknowledge the help offered by all members of stackoverlow which gave me unthinkable perspectives to look at the problem at hand. Thanks guys, cheers!!!!!!
1,135,560
1,135,582
Pointer to Value in a std::map
I have a std::map that is used by multiple threads to store data. The map is declared like this: std::map<int, Call> calls; From each thread, I have to acquire a mutex lock, obtain a pointer or reference to the object belonging to that thread, then release the mutex lock. I can modify the object after that because each object is used only by one thread. As soon as the thread dies, the corresponding pair in the map would also get deleted. I would like to know the best way to implement this. I was thinking of two ways: 1) I know this one could look outrageously crazy, but still std::map<int, Call> calls; ... { mutex.lock(); Call* callptr = &calls[id]; mutex.unlock(); // use callptr } or 2) I think this one looks more sensible std::map<int, std::auto_ptr<Call> > calls; ... { mutex.lock(); std::auto_ptr<Call> callptr = map[id]; mutex.unlock(); // use callptr mutex.lock(); map[id] = callptr; mutex.unlock(); } The threads actually are created in a different dll and I don't have the code for that. This dll that I'm writing now gets imported by that dll and used. So it has to be implemented with std::map only, but could anyone tell me if one of these methods is ok or if there are ways to make it more stable. Thanks
You should use iterators: mutex.lock(); std::map<int, Call>::iterator callptr = calls.find(id); callptr->second.foo(); ... mutex.unlock(); Your first solution with pointers is problematic, because the lifetime of the object in the map is uncertain - it may be moved when the tree is rebalanced when elements are inserted or deleted. Your second solution won't work at all, because std::auto_ptr does not fulfil the requirements for mapped_type of std::map - mostly because its copy constructor and operator= don't actually copy. You likely won't get a compiler error, but you'll get very weird behavior at run-time.
1,135,822
1,135,834
Escaping a # symbol in a #define macro?
Without going into the gory details I want to use a #define macro that will expand to a #include but the '#' sign is confusing the preprocessor (as it thinks I want to quote an argument.) For example, I want to do something like this: #define MACRO(name) #include "name##foo" And use it thus: MACRO(Test) Which will expand to: #include "Testfoo" The humble # sign is causing the preprocessor to barf. MinGW gives me the following error: '#' is not followed by a macro parameter I guess I need to escape the # sign but I don't if this is even possible. Yes, macros are indeed evil...
As far as I remember you cannot use another preprocessor directive in define.
1,135,841
1,135,862
C++ multiline string literal
Is there any way to have multi-line plain-text, constant literals in C++, à la Perl? Maybe some parsing trick with #includeing a file? I can't think of one, but boy, that would be nice. I know it'll be in C++0x.
Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler: const char *text = "This text is pretty long, but will be " "concatenated into just a single string. " "The disadvantage is that you have to quote " "each part, and newlines must be literal as " "usual."; The indentation doesn't matter, since it's not inside the quotes. You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile: const char *text2 = "Here, on the other hand, I've gone crazy \ and really let the literal span several lines, \ without bothering with quoting each line's \ content. This works, but you can't indent."; Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, so that everything acts as if the newline wasn't there. You don't get newlines in the string at the locations where you had backslashes. With this form, you obviously can't indent the text since the indentation would then become part of the string, garbling it with random spaces.
1,135,901
1,135,967
Windows message loop
Theres some reason for this code not reach the first else? I got it exactly the same from vairous sources. Than I did my own encapsulation. Everything goes fine. Window is created, messages are treated, events are generated to keyborad input in the client area, the gl canvas works fine (when I force it to draw). The only problem is that message loop never leaves the first if. :/ I'm really stuck. while (!done) { if (::PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { done = TRUE; } else { ::TranslateMessage (&msg); ::DispatchMessage (&msg); } } else { // Code is never reaching this! draw (); ::SwapBuffers(hDC); idle (); } } return msg.wParam;
In your case the message queue must never be empty - why? Well it depends on what the rest of your program is doing. Some possibilities: Your code is posting new messages to the queue in a manner such that the queue doesn't get empty. I'd suggest logging out the message ids as they are handled. You aren't handling paint messages - from msdn: "The PeekMessage function normally does not remove WM_PAINT messages from the queue. WM_PAINT messages remain in the queue until they are processed. However, if a WM_PAINT message has a NULL update region, PeekMessage does remove it from the queue." Hope this helps. [Edit] To handle WM_PAINT either call BeginPaint and EndPaint or forward to DefWindowProc
1,136,115
1,136,129
creating a vector of pointers that point to more vectors
I am trying to create a vector that contains pointers, each pointer points to another vector of a type Cell which I have made using a struct. The for loop below allows me to let the user define how many elements there are in the vector of pointers. Here's my code: vector< vector<Cell>* > vEstore(selection); for (int t=0; t<selection; t++) { vEstore[t] = new vector<Cell>; vEstore[t]->reserve(1000); } This, I think, gives me a vector of pointers to destination vectors of the type Cell. This compiles but I'm now trying to push_back onto the destination vectors and can't see how to do it. Since the destination vector is of the type Cell which is made from a type as follows: struct Cell { unsigned long long lr1; unsigned int cw2; }; I can't work out how to push_back onto this destination vector with 2 values? I was thinking ... binpocket[1]->lr1.push_back(10); binpocket[1]->cw2.push_back(12); As I thought this would dereference the pointer at binpocket[1] revealing the destination array values, then address each element in turn. But it doesn't compile. can anyone help ...but this only has one value and doesn't compile anyway.
Cell cell = { 10, 12 }; binpocket[1]->push_back(cell); Alternatively, you can give your struct a constructor. struct Cell { Cell() {} Cell(unsigned long long lr1, unsigned int cw2) : lr1(lr1), cw2(cw2) { } unsigned long long lr1; unsigned int cw2; }; Then you could do binpocket[1]->push_back(Cell(10, 12)); Note that long long is non-standard (yet), but is a generally accepted extension.
1,136,249
1,136,255
How to call Base class method through base class pointer pointing to derived class
class Base { public: virtual void foo() {} }; class Derived: public Base { public: virtual void foo() {} }; int main() { Base *pBase = NULL; Base objBase; Derived objDerived; pBase = &objDerived; pBase->foo(); /*Here Derived class foo will be called, but i want this to call a base class foo. Is there any way for this to happen? i.e. through casting or something? */ }
pBase->Base::foo()
1,136,323
1,136,971
Adding generic logging support in C++ shared library
I'm writing a c++ shared library that is intended to be used by other library or executable. What is the best way to add a generic logging in my library? Ideally I'd like to adapt my library to logging functionality chosen by the library's user. Suppose i have a class in my library class A { public: void method(string param1, int param2); } void A::method(string param1, int param2){ /* i want to log values of param1 and param2, but actual logging method must be defined outside of my library. Maybe some kind of macro should help here. */ /*e.g.*/ GENERICLOG_DEBUG("param1=" + param1+ " param2="+param1); /*if so, what that macro body should look like ? */ } I don't want to make my library tied to any log4XXX specific API.
You can provide a callback mechanism to allow the library's user to provide your library with an adapter into their logging. I.e., in your library provide an abstract logging interface class, e.g.: class Logger { public: virtual ~Logger () {} virtual void log (const std::string& message) = 0; }; and a class to regster a Logger with: class Log { private: static Logger* logger_; public: static void registerLogger (Logger& logger) { logger_ = &logger; } static void log (const std::string& message) { if (logger_ != 0) logger_->log (message); } }; Your library then logs with something like: Log::log ("My log message"); The application using your library should provide an implementation of Logger (i.e. a concrete subclass) and register it with your Log class. Their Logger impl will implement logging as they see fit. This allows your library to be used by applications which use different logging libraries. Note the above code is basic and untested. In practice you may want to change the log methods to include a logging level parameter, etc.
1,136,359
1,137,153
How to force std::stringstream operator >> to read an entire string?
How to force std::stringstream operator >> to read an entire string instead of stopping at the first whitespace? I've got a template class that stores a value read from a text file: template <typename T> class ValueContainer { protected: T m_value; public: /* ... */ virtual void fromString(std::string & str) { std::stringstream ss; ss << str; ss >> m_value; } /* ... */ }; I've tried setting/unsetting stream flags but it didn't help. Clarification The class is a container template with automatic conversion to/from type T. Strings are only one instance of the template, it must also support other types as well. That is why I want to force operator >> to mimic the behavior of std::getline.
As operator >> is not satisfying our requirement when T=string, we can write a specific function for [T=string] case. This may not be the correct solution. But, as a work around have mentioned. Please correct me if it won't satisfy your requirement. I have written a sample code as below: #include <iostream> #include <sstream> #include <string> using namespace std; template <class T> class Data { T m_value; public: void set(const T& val); T& get(); }; template <class T> void Data<T>::set(const T& val) { stringstream ss; ss << val; ss >> m_value; } void Data<string>::set(const string& val) { m_value = val; } template <class T> T& Data<T>::get() { return m_value; } int main() { Data<int> d; d.set(10); cout << d.get() << endl; Data<float> f; f.set(10.33); cout << f.get() << endl; Data<string> s; s.set(string("This is problem")); cout << s.get() << endl; }
1,136,900
54,747,631
RTP sequence extract
A RTP packet consists of a 12-byte RTP header and subsequent RTP payload The 3rd and 4th byte of the header contain the Most-Significant-Byte and Least-Significant-Byte of the sequence number of the RTP packet Seq Num= (MSB<<8)+LSB char pszPacket[12]; ... long lSeq = ???? - How to get the sequence number from a packet?
If you need a proper implementation for that: typedef struct _RTPHeader { //first byte #if G_BYTE_ORDER == G_LITTLE_ENDIAN unsigned int CC:4; /* CC field */ unsigned int X:1; /* X field */ unsigned int P:1; /* padding flag */ unsigned int version:2; #elif G_BYTE_ORDER == G_BIG_ENDIAN unsigned int version:2; unsigned int P:1; /* padding flag */ unsigned int X:1; /* X field */ unsigned int CC:4; /* CC field*/ #else #error "G_BYTE_ORDER should be big or little endian." #endif //second byte #if G_BYTE_ORDER == G_LITTLE_ENDIAN unsigned int PT:7; /* PT field */ unsigned int M:1; /* M field */ #elif G_BYTE_ORDER == G_BIG_ENDIAN unsigned int M:1; /* M field */ unsigned int PT:7; /* PT field */ #else #error "G_BYTE_ORDER should be big or little endian." #endif guint16 seq_num; /* length of the recovery */ guint32 TS; /* Timestamp */ guint32 ssrc; } RTPHeader; //12 bytes And what you can do is: char pszPacket[12]; RTPHeader* myRTPPacket = (RTPHeader*) pszPacket; printf("Sequence number is: %hu", myRTPPacket->seq_num;