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
387,633
387,667
Dispatching exceptions in C++
How should exceptions be dispatched so that error handling and diagnostics can be handled in a centralized, user-friendly manner? For example: A DataHW class handles communication with some data acquisition hardware. The DataHW class may throw exceptions based on a number of possible errors: intermittent signal, no signal, CRC failure, driver error. Each type of error gets its own exception class. The DataHW class is called by a number of different pieces of code that do different types of acquisition and analysis. The proper error handling strategy depends on the type of exception and the operation being attempted. (On intermittent signal, retry X times then tell the user; on a driver error, log an error and restart the driver; etc.) How should this error handling strategy be invoked? Coding error recovery into each exception class: This would result in exception classes that are rather large and contain high-level UI and system management code. This seems bad. Providing a separate catch block for each type of exception: Since the DataHW class is called from many different places, each catch block would have to be duplicated at each call site. This seems bad. Using a single catch block that calls some ExceptionDispatch function with a giant RTTI-based switch statement: RTTI and switch usually indicates a failure to apply OO design, but this seems the least bad alternative.
Avoid duplicating the catch blocks at each call site by catching (...) and calling a shared handler function which rethrows and dispatches: f() { try { // something } catch (...) { handle(); } } void handle() { try { throw; } catch (const Foo& e) { // handle Foo } catch (const Bar& e) { // handle Bar } // etc }
387,654
387,781
Why is there no Z80 like LDIR functionality in C/C++/rtl?
In Z80 machine code, a cheap technique to initialize a buffer to a fixed value, say all blanks. So a chunk of code might look something like this. LD HL, DESTINATION ; point to the source LD DE, DESTINATION + 1 ; point to the destination LD BC, DESTINATION_SIZE - 1 ; copying this many bytes LD (HL), 0X20 ; put a seed space in the first position LDIR ; move 1 to 2, 2 to 3... The result being that the chunk of memory at DESTINATION is completely blank filled. I have experimented with memmove, and memcpy, and can't replicate this behavior. I expected memmove to be able to do it correctly. Why do memmove and memcpy behave this way? Is there any reasonable way to do this sort of array initialization? I am already aware of char array[size] = {0} for array initialization I am already aware that memset will do the job for single characters. What other approaches are there to this issue?
I believe this goes to the design philosophy of C and C++. As Bjarne Stroustrup once said, one of the major guiding principles of the design of C++ is "What you don’t use, you don’t pay for". And while Dennis Ritchie may not have said it in exactly those same words, I believe that was a guiding principle informing his design of C (and the design of C by subsequent people) as well. Now you may think that if you allocate memory it should automatically be initialized to NULL's and I'd tend to agree with you. But that takes machine cycles and if you're coding in a situation where every cycle is critical, that may not be an acceptable trade-off. Basically C and C++ try to stay out of your way--hence if you want something initialized you have to do it yourself.
387,792
388,068
Vim indentation for c++ templates?
Does anyone have or know about vim plugin/macro/function that indents nicely c++ templates? When I highlight template definition in vim .hpp/.h file and indent it with '=' I get something like this: > template < > class TFilter, > class TParser, > class TConsumer, > class TDataProcessor, > class TDataFeed, > class TSymbolMap > > > struct DataFeedTraits > { > typedef TFilter Filter; > typedef TParser<TSymbolMap> Parser; > typedef TConsumer<Parser> Consumer; > typedef TDataProcessor<Filter,Consumer> DataProcessor; > typedef TDataFeed<Filter,DataProcessor,Parser,Ccnsumer> DataFeed; > }; I think the cindent aligns the struct/class declaration with the closing bracket '>'. I would like to end up with something like this, or similar, exact formatting does not matter, as far as it is formatted: template < class TFilter, class TParser, class TConsumer, class TDataProcessor, class TDataFeed, class TSymbolMap > struct DataFeedTraits { typedef TFilter Filter; typedef TParser<TSymbolMap> Parser; typedef TConsumer<Parser> Consumer; typedef TDataProcessor<Filter,Consumer> DataProcessor; typedef TDataFeed<Filter,DataProcessor,Parser,Ccnsumer> DataFeed; };
You can use the identexpr option to specify indent by evaluating an expression (i.e. writing a vim script function). This function should accept a string -- the line -- and return the number of spaces to indent. This gives you the flexibility to return an indent level for this template condition, or fall-back to autoindent, smartindent or cindent in normal, C-like situations. Here is an example that was created to handle the signals and slots extension of Qt. It demonstrates fall-back to the cindent function.
387,936
389,299
How to detect leaks under WinCE C/C+ runtime library?
I know the possibilities of basic leak detection for Win32 using the crtdbg.h header, but this header is unavailable in the CE CRT library headers (i'm using the lastest SDK v6.1). Anyone knows how I can automatically detect leaks in a WinCE/ARMV4I configuration with VC 9.0? I don't want to override new/delete for my class hierarchy, I would prefer ready to use and tested code.
At work (developing WindowsCE based OS + Applications) we have created our own memory manager, roughly based on the Fluid Studios Memory Manager (the link which I found using SO!). I'm pretty sure with a few simple modifications you could adapt it to use on your platform. Basically it doesn't override new and delete, but instead uses the preprocessor to add extra reporting to it. Then once the program exits it generates an output file of memory leaks.
388,200
388,305
Architectural Suggestions in a Linux App
I've done quite a bit of programming on Windows but now I have to write my first Linux app. I need to talk to a hardware device using UDP. I have to send 60 packets a second with a size of 40 bytes. If I send less than 60 packets within 1 second, bad things will happen. The data for the packets may take a while to generate. But if the data isn't ready to send out on the wire, it's ok to send the same data that was sent out last time. The computer is a command-line only setup and will only run this program. I don't know much about Linux so I was hoping to get a general idea how you might set up an app to meet these requirements. I was hoping for an answer like: Make 2 threads, one for sending packets and the other for the calculations. But I'm not sure it's that simple (maybe it is). Maybe it would be more reliable to make some sort of daemon that just sent out packets from shared memory or something and then have another app do the calculations? If it is some multiple process solution, what communication mechanism would you recommend? Is there some way I can give my app more priority than normal or something similar? PS: The more bulletproof the better!
I posted this answer to illustrate a quite different approach to the "obvious" one, in the hope that someone discovers it to be exactly what they need. I didn't expect it to be selected as the best answer! Treat this solution with caution, because there are potential dangers and concurrency issues... You can use the setitimer() system call to have a SIGALRM (alarm signal) sent to your program after a specified number of milliseconds. Signals are asynchronous events (a bit like messages) that interrupt the executing program to let a signal handler run. A set of default signal handlers are installed by the OS when your program begins, but you can install a custom signal handler using sigaction(). So all you need is a single thread; use global variables so that the signal handler can access the necessary information and send off a new packet or repeat the last packet as appropriate. Here's an example for your benefit: #include <stdio.h> #include <signal.h> #include <sys/time.h> int ticker = 0; void timerTick(int dummy) { printf("The value of ticker is: %d\n", ticker); } int main() { int i; struct sigaction action; struct itimerval time; //Here is where we specify the SIGALRM handler action.sa_handler = &timerTick; sigemptyset(&action.sa_mask); action.sa_flags = 0; //Register the handler for SIGALRM sigaction(SIGALRM, &action, NULL); time.it_interval.tv_sec = 1; //Timing interval in seconds time.it_interval.tv_usec = 000000; //and microseconds time.it_value.tv_sec = 0; //Initial timer value in seconds time.it_value.tv_usec = 1; //and microseconds //Set off the timer setitimer(ITIMER_REAL, &time, NULL); //Be busy while(1) for(ticker = 0; ticker < 1000; ticker++) for(i = 0; i < 60000000; i++) ; }
388,878
388,988
Registering derived classes in C++
EDIT: minor fixes (virtual Print; return mpInstance) following remarks in the answers. I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class. All the objects that create and use the base class objects shouldn't change the way they create or call an object, i.e. should continue calling BaseClass.Create() even when they actually create a Child class. The Base classes know that they can be overridden, but they do not know the concrete classes that override them. And I want the registration of all the the Child classes to be done just in one place. Here is my implementation: class CAbstractFactory { public: virtual ~CAbstractFactory()=0; }; template<typename Class> class CRegisteredClassFactory: public CAbstractFactory { public: ~CRegisteredClassFactory(){}; Class* CreateAndGet() { pClass = new Class; return pClass; } private: Class* pClass; }; // holds info about all the classes that were registered to be overridden class CRegisteredClasses { public: bool find(const string & sClassName); CAbstractFactory* GetFactory(const string & sClassName) { return mRegisteredClasses[sClassName]; } void RegisterClass(const string & sClassName, CAbstractFactory* pConcreteFactory); private: map<string, CAbstractFactory* > mRegisteredClasses; }; // Here I hold the data about all the registered classes. I hold statically one object of this class. // in this example I register a class CChildClass, which will override the implementation of CBaseClass, // and a class CFooChildClass which will override CFooBaseClass class RegistrationData { public: void RegisterAll() { mRegisteredClasses.RegisterClass("CBaseClass", & mChildClassFactory); mRegisteredClasses.RegisterClass("CFooBaseClass", & mFooChildClassFactory); }; CRegisteredClasses* GetRegisteredClasses(){return &mRegisteredClasses;}; private: CRegisteredClasses mRegisteredClasses; CRegisteredClassFactory<CChildClass> mChildClassFactory; CRegisteredClassFactory<CFooChildClass> mFooChildClassFactory; }; static RegistrationData StaticRegistrationData; // and here are the base class and the child class // in the implementation of CBaseClass::Create I check, whether it should be overridden by another class. class CBaseClass { public: static CBaseClass* Create() { CRegisteredClasses* pRegisteredClasses = StaticRegistrationData.GetRegisteredClasses(); if (pRegisteredClasses->find("CBaseClass")) { CRegisteredClassFactory<CBaseClass>* pFac = dynamic_cast<CRegisteredClassFactory<CBaseClass>* >(pRegisteredClasses->GetFactory("CBaseClass")); mpInstance = pFac->CreateAndGet(); } else { mpInstance = new CBaseClass; } return mpInstance; } virtual void Print(){cout << "Base" << endl;}; private: static CBaseClass* mpInstance; }; class CChildClass : public CBaseClass { public: void Print(){cout << "Child" << endl;}; private: }; Using this implementation, when I am doing this from some other class: StaticRegistrationData.RegisterAll(); CBaseClass* b = CBaseClass::Create(); b.Print(); I expect to get "Child" in the output. What do you think of this design? Did I complicate things too much and it can be done easier? And is it OK that I create a template that inherits from an abstract class? I had to use dynamic_pointer (didn't compile otherwise) - is it a hint that something is wrong? Thank you.
This sort of pattern is fairly common. I'm not a C++ expert but in Java you see this everywhere. The dynamic cast appears to be necessary because the compiler can't tell what kind of factory you've stored in the map. To my knowledge there isn't much you can do about that with the current design. It would help to know how these objects are meant to be used. Let me give you an example of how a similar task is accomplished in Java's database library (JDBC): The system has a DriverManager which knows about JDBC drivers. The drivers have to be registered somehow (the details aren't important); once registered whenever you ask for a database connection you get a Connection object. Normally this object will be an OracleConnection or an MSSQLConnection or something similar, but the client code only sees "Connection". To get a Statement object you say connection.prepareStatement, which returns an object of type PreparedStatement; except that it's really an OraclePreparedStatement or MSSQLPreparedStatement. This is transparent to the client because the factory for Statements is in the Connection, and the factory for Connections is in the DriverManager. If your classes are similarly related you may want to have a function that returns a specific type of class, much like DriverManager's getConnection method returns a Connection. No casting required. The other approach you may want to consider is using a factory that has a factory-method for each specific class you need. Then you only need one factory-factory to get an instance of the Factory. Sample (sorry if this isn't proper C++): class CClassFactory { public: virtual CBaseClass* CreateBase() { return new CBaseClass(); } virtual CFooBaseClass* CreateFoo() { return new CFooBaseClass();} } class CAImplClassFactory : public CClassFactory { public: virtual CBaseClass* CreateBase() { return new CAImplBaseClass(); } virtual CFooBaseClass* CreateFoo() { return new CAImplFooBaseClass();} } class CBImplClassFactory : public CClassFactory // only overrides one method { public: virtual CBaseClass* CreateBase() { return new CBImplBaseClass(); } } As for the other comments criticizing the use of inheritance: in my opinion there is no difference between an interface and public inheritance; so go ahead and use classes instead of interfaces wherever it makes sense. Pure Interfaces may be more flexible in the long run but maybe not. Without more details about your class hierarchy it's impossible to say.
388,934
389,053
Aligning Member Variables By Template Type
I want to align my member variables based on a class template type but I'm not sure if it is actually possible. The following is a (very) simple example of what I'd like to do template<int Align> class MyClass { private: struct MyStruct { // Some stuff } __declspec(align(Align)); __declspec(align(Align)) int myAlignedVariable; }; So what I'd like is for Align to be a per-instance variable, and only through that is the align value of the class contents decided. Unfortunately I always get the following error error C2975: 'test::MyClass' : invalid template argument for 'Align', expected compile-time constant expression So, is this actually possible or can the alignment only be possible using a fixed compile time constant? If not, can anyone think of a way around this? Thanks :)
Custom alignment isn't in the standard, so how the compilers deal with it is up to them - looks like VC++ doesn't like combining templates with __declspec. I suggest a work-around using specialisation, something like this: template<int A> struct aligned; template<> struct aligned<1> { } __declspec(align(1)); template<> struct aligned<2> { } __declspec(align(2)); template<> struct aligned<4> { } __declspec(align(4)); template<> struct aligned<8> { } __declspec(align(8)); template<> struct aligned<16> { } __declspec(align(16)); template<> struct aligned<32> { } __declspec(align(32)); and then derive from that in your code: template<int Align> class MyClass { private: struct MyStruct : aligned<Align> { // stuff }; }; This unfortunately breaks the POD-ness of MyStruct. It also doesn't work with built-in/existing types, so you'll have to use a wrapper for those. aligned_t<int, 4> myAlignedVariable;
389,069
389,074
Programmatically reading a web page
I want to write a program in C/C++ that will dynamically read a web page and extract information from it. As an example imagine if you wanted to write an application to follow and log an ebay auction. Is there an easy way to grab the web page? A library which provides this functionality? And is there an easy way to parse the page to get the specific data?
Have a look at the cURL library: #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se"); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); } return 0; } BTW, if C++ is not strictly required. I encourage you to try C# or Java. It is much easier and there is a built-in way.
389,244
389,338
Best way to use a VB.NET class library from a C++ DLL?
I need to use one of my VB.NET projects in a C++ project. The interface between the two will be for the C++ code to instantiate and call methods on one of the .NET assembly objects. Both compile to DLLs (and then the C++ DLL is loaded from the NTVDM as a VDD, but that's probably not relevant.) If possible I would like to avoid using COM for this as I need to deploy without touching the registry. Also, I am using Visual Studio 2008 Express editions for both C++ and VB.NET. Please, what is the best way to do this?
Do you really need native C++ or can you use C++/CLI? If you can do it all in C++/CLI, then you'll end up with a pure .NET application. If you need 'native' C++, then you can create an assembly that includes managed and unmanaged C++ directly from Visual Studio (the native C++ calls C++/CLI which then calls through to your VB.NET). And, if you'd prefer to have the whole lot in a single assembly you can follow the instructions for linking native C++ into C# applications. It should work for VB.NET too. And I'd highly recommend "Expert C++/CLI" by Heege (1‐59059‐756‐7)
389,922
389,944
C++ namespace and include
Why do we need both using namespace and include directives in C++ programs? For example, #include <iostream> using namespace std; int main() { cout << "Hello world"; } Why is it not enough to just have #include <iostream> or just have using namespace std and get rid of the other? (I am thinking of an analogy with Java, where import java.net.* will import everything from java.net, you don't need to do anything else.)
In C++ the concepts are separate. This is by design and useful. You can include things that without namespaces would be ambiguous. With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted. Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.
389,957
389,963
Forward Declaration of a Base Class
I'm trying to create proper header files which don't include too many other files to keep them clean and to speed up compile time. I encountered two problems while doing this: Forward declaration on base classes doesn't work. class B; class A : public B { // ... } Forward declaration on STD classes doesn't work. namespace std { class string; } class A { string aStringToTest; } How do I solve these problems?
The first problem you can't solve. The second problem is not anything to do with standard library classes. It's because you declare an instance of the class as a member of your own class. Both problems are due to the requirement that the compiler must be able to find out the total size of a class from its definition. However, the compiler can work out the size of a pointer to a class, even if it doesn't yet have the full definition of it. So a possible solution in such cases is to have a pointer (or reference) member in the consuming class. Not much help in the base class case, because you won't get an 'is a' relationship. Nor is it worth doing for something like std::string. Firstly, it's supposed to be a convenient wrapper around a character buffer, to save you from doing memory management on something so simple. If you then hold a pointer to it, just to avoid including the header, you're probably taking a good idea too far. Secondly (as pointed out in a comment), std::string is a typedef to std::basic_string<char>. So you need to forward declare (and then use) that instead, by which time things are getting very obscure and hard to read, which is another kind of cost. Is it really worth it?
390,102
390,163
Memory allocation and deallocation across threads
I'm still trying to debug a very sneaky memory corruption problem. I came across a section of my code that allocates memory on one thread and deletes it on another. I have a vague feeling that this is wrong, but I'm not sure why. The threads share the process memory and access to these structures is protected by a mutex, so I think everything would work. However, is it there any danger I'm not seeing?
As indicated in another answer by @monjardin, there is nothing inherently wrong with what you are trying to do. As an additional thought, you didn't mention the platform, etc. you are running into this problem on but if multi-threading is new to you and/or this application you are working on, you want to be sure that the standard support libraries you are using are the thread safe versions of the libraries. In many environments/platforms they have both the single threaded and multi-threaded versions of the support libraries available to the developer. If you are using threads but linking against the single thread version of the libraries, lots of bad things could be happening. For example, in a single threaded support library for malloc() and free() it would not have mutex protection for the heap (as an optimization). The multi-thread version of the library would add mutex protection to the heap manager to support more than one thread manipulating the heap at a time. (This is just one example).
390,615
390,623
Implementation of finally in C++
Is this a good way to implement a Finally-like behavior in standard C++? (Without special pointers) class Exception : public Exception { public: virtual bool isException() { return true; } }; class NoException : public Exception { public: bool isException() { return false; } }; Object *myObject = 0; try { // OBJECT CREATION AND PROCESSING try { myObject = new Object(); // Do something with myObject. } // EXCEPTION HANDLING catch (Exception &e) { // When there is an excepion, handle or throw, // else NoException will be thrown. } throw NoException(); } // CLEAN UP catch (Exception &e) { delete myObject; if (e.isException()) throw e; } No exception thrown by object -> NoException -> Object cleaned up Exception thrown by object -> Handled -> NoException -> Object cleaned up Exception thrown by object -> Thrown -> Exception -> Object cleaned up -> Thrown
The standard answer is to use some variant of resource-allocation-is-initialization abbreviated RAII. Basically you construct a variable that has the same scope as the block that would be inside the block before the finally, then do the work in the finally block inside the objects destructor. try { // Some work } finally { // Cleanup code } becomes class Cleanup { public: ~Cleanup() { // Cleanup code } } Cleanup cleanupObj; // Some work. This looks terribly inconvenient, but usually there's a pre-existing object that will do the clean up for you. In your case, it looks like you want to destruct the object in the finally block, which means a smart or unique pointer will do what you want: std::unique_ptr<Object> obj(new Object()); or modern C++ auto obj = std::make_unique<Object>(); No matter which exceptions are thrown, the object will be destructed. Getting back to RAII, in this case the resource allocation is allocating the memory for the Object and constructing it and the initialization is the initialization of the unique_ptr.
390,789
391,097
keep a formless application from closing for a keyboard hook
I am working on a c++ win32 program that involves a keyboard hook. The application is a win32 project with no user interface whatsoever. I need to keep the application from closing without using causing the hook to not work or use up a bunch of system resources. I used to use a message box but I need the application to be completely invisible. Any help would be appreciated! If you have any questions just ask.
I think what you need is message only window (MSDN says) A message-only window enables you to send and receive messages. It is not visible, has no z-order, cannot be enumerated, and does not receive broadcast messages. The window simply dispatches messages.
390,997
391,015
When virtual doesn't work
I have a weird error in my C++ classes at the moment. I have an ActiveX wrapper class (as part of wxWidgets) that i added a new virtual function to. I have another class that inherits from the ActiveX one (wxIEHtmlWin) however the ActiveX class always calls its own function instead of the one in wxIEHtmlWin which overrides it. I can't work out why this is happening. I made the function pure virtual and now the program crashes when it does the function call but compiles fine otherwise. Is there any way to disable virtual functions or have I found a bug in Visual Studio? ActiveX class protected: virtual FrameSite* getNewFrameSite()=0; wxIEHtmlWin class class wxIEHtmlWin : public wxActiveX { protected: FrameSite* getNewFrameSite(); } FrameSite* wxIEHtmlWin::getNewFrameSite() { return new gcFrameSite(this); } Edit: I've added another test function (returns an int) and still screws up. Link to code in question: http://lodle.net/public/iebrowser.rar Edit: OK thanks to the answer below i got it to work. What i did was create the activex class in two parts (like suggested) however in wxIEHtmlWin i called the second part in the constructor code. Like so: wxIEHtmlWin::wxIEHtmlWin(wxWindow * parent, wxWindowID id, const wxPoint& pos,const wxSize& size,long style, const wxString& name) : wxActiveX() { wxActiveX::Create(parent, PROGID, id, pos, size, style, name); SetupBrowser(); } Now i know why wxWidgets supports two part construction.
You are calling the virtual method from within the class's constructor (via another call). This will call the method on the current class as the sub-class hasn't been constructed yet. The fix is to use an init() method and call it after constructing the class. i.e something like this: class wxActivex { wxActivex() {} virtual void init() { getNewFrame(); } }; // in the code that uses these classes: wxActivex *activex = new IEHtmlFrame(); activex->init();
391,022
391,675
Local WideString variable debug error "Int3 DbgBreakPoint"
In C++Builder, I wrote the following code (in Button1Click handler), When I run in debug mode, I get the "Int3 DbgBreakPoint" (Stack corrupted?). This doesn't happen for AnsiSting (Maybe reference counting). WideString boshluq; boshluq=L" "; Is this normal? What do you suggest me to fix this code?
WideStrings are pointer referenced variables for Windows WideStrings, maybe the problem is in your windows system library. I have the same problem with breakpoint in the ntdll.dll, I dont know if it is the same for you. I solve with this unit http://www.tbosystems.bluehosting.com.br/dbx4/int3.pas (Thanks to Leonel Togniolli), maybe you can check this out and see if can help you out, or try the same code in other windows machine.
391,125
391,324
How to change pane text of status bar from a thread in MFC?
I have a dialog in MFC with a CStatusBar. In a separate thread, I want to change the pane text of status bar. However MFC complains with asserts? How is it done? An example code would be great.
You could post a private message to the main frame window and 'ask' it to update the status bar. The thread would need the main window handle (don't use the CWnd object as it won't be thread safe). Here is some sample code: static UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam); void CMainFrame::OnCreateTestThread() { // Create the thread and pass the window handle AfxBeginThread(UpdateStatusBarProc, m_hWnd); } LRESULT CMainFrame::OnUser(WPARAM wParam, LPARAM) { // Load string and update status bar CString str; VERIFY(str.LoadString(wParam)); m_wndStatusBar.SetPaneText(0, str); return 0; } // Thread proc UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam) { const HWND hMainFrame = reinterpret_cast<HWND>(pParam); ASSERT(hMainFrame != NULL); ::PostMessage(hMainFrame, WM_USER, IDS_STATUS_STRING); return 0; } The code is from memory as I don't have access to compiler here at home, so apologies now for any errors. Instead of using WM_USER you could register your own Windows message: UINT WM_MY_MESSAGE = ::RegisterWindowsMessage(_T("WM_MY_MESSAGE")); Make the above a static member of CMainFrame for example. If using string resources is too basic then have the thread allocate the string on the heap and make sure the CMainFrame update function deletes it, e.g.: // Thread proc UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam) { const HWND hMainFrame = reinterpret_cast<HWND>(pParam); ASSERT(hMainFrame != NULL); CString* pString = new CString; *pString = _T("Hello, world!"); ::PostMessage(hMainFrame, WM_USER, 0, reinterpret_cast<LPARAM>(pString)); return 0; } LRESULT CMainFrame::OnUser(WPARAM, LPARAM lParam) { CString* pString = reinterpret_cast<CString*>(lParam); ASSERT(pString != NULL); m_wndStatusBar.SetPaneText(0, *pString); delete pString; return 0; } Not perfect, but it's a start.
391,532
391,615
Send HTTP request from VC++ file
I am trying to send an HTTP request with the contents of a file set as the body of the HTTP request and want to get the response from a server using VC++. Any help is appreciated. Thanks. I think I was not very clear with what I wanted to do or I misunderstood the answers. Neways, what I want to accomplish is, one of my web-services accepts the data of a local file as the body of the HTTP request sent to it. I want to make a call to this service and send the contents of a txt file as the body of the HTTP request. In return I will get a response from the service which I want to get in a string variable. Thanks.
You can use cURL library. There is also a similar topic Programmatically reading a web page
391,553
391,567
Is there any cheatsheet available for C++?
What do you like to have in the C++ cheat sheet?
I found this one that seems to be detailed enough. It covers basics of templates, inheritance, operators, exceptions, etc. It has a lot of information in a very small space.
391,595
391,616
When is it OK to throw an exception from a destructor in C++?
I know the rule is to NEVER throw one during a destructor, and I understand why. I would not dare do it. But even the C++ Faq Lite says that this rule is good 99% of the time. What is the other 1% that they fail to delve into? Link to the C++ Faq Lite bullet point on throwing from ~():
Just don't do it. If the stars and planets align in such a way that you find you need to... Still don't do it.
391,693
391,745
Strange DLL + InterropServices problem
I'm trying to learn the basics of tying up unmanaged C++ and .NET. So, I've got the DLL compiled and callable from C#. Great. Now I run into this weird problem: Here's my C++ file, Main.cpp: #include <stdio.h> extern "C" __declspec(dllexport) void DisplayHelloFromDLL() { printf ("Hello from the World of 1986!\n"); } and C# file, Program.cs: using System; using System.Runtime.InteropServices; namespace FancyApp { class Program { [DllImport("ConsoleApp.dll")] public static extern void DisplayHelloFromDLL(); static void Main() { Console.WriteLine("Hello form the World of 2008!"); DisplayHelloFromDLL(); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } } Simple enough. When build, I get ConsoleApp.dll from the C++ side, and FancyApp.exe from C#. When run, it outputs Hello form the World of 2008! Hello from the World of 1986! Press any key to exit as it should, except in Release mode from VS2008 (Press F5), I get Hello form the World of 2008! Press any key to exit Now, if I go to Explorer and run the release build of FancyApp.exe without VS, it runs fine. Ideas? I've uploaded my solutions folder here (180kb).
Well I see the same behavior here, and I can't fully explain it. However I think that trying to run in debug mode (F5) against a Release build, you should expect undefined behavior. If I use ctrl-F5 it runs properly. Since that's working, we can deduce that the binary is correctly built, so there's no compiler issue, but instead you're seeing some strange artifact of the debugger. This can be proven by going into the properties of FancyApp and on the Debug tab unchecking 'Enable the Visual Studio hosting process'. If you do that it works as you're expecting. Why, exactly, I can't say. The lesson here is don't try to debug a release build.
391,756
391,763
Can an anonymous object be declared static in C++?
Is this allowed? : class A; void foo() { static A(); } I get signal 11 when I try to do it, but the following works fine: class A; void foo() { static A a; } Thank you.
Nope. There is no such thing as an "anonymous object" in C++. There is such a thing as defining an object to type A that is immediately discarded; what you've written is an expression that returns an A object that's never assigned to a variable, like the return code of printf usually is never assigned or used. In that code, if it worked, you'd be declaring "no object" to be allocated outside the heap. Since there's no object to allocate, it's meaningless.
391,772
391,941
How do I append children to QDomDocumentFragment object in qt with c++
I'm using qt 4.4.3 with c++. I want to implement a QDomDocumentFragment object, and pass it as a return value for a function. I am using it the same way as QDomElement objects, with appendChild(): QDomDocumentFragment rootnode; QDomNode initmodnode = doc.createElement("initmod"); QDomText initmodval = doc.createTextNode("4"); initmodnode.appendChild(initmodval); rootnode.appendChild(initmodnode); After inserting 7 other nodes in this way, and returning from the function, I noticed that calling insertAfter() on a QDomElement node with the returned QDomDocumentFragment was not inserting any new children. After debugging with the following code inside the function, I realized no nodes were actually getting inserted into rootnode: QMessageBox::information(this->owner, QObject::tr("Debug"), QObject::tr("Node has children: ")+QString::number(rootnode.childNodes().size())); The Message printed was "Node has children: 0". What am I missing here?
Ok sorry for wasting everyone's time.. looks like I needed to create the document fragment using: QDomDocumentFragment rootnode = doc.createDocumentFragment();
391,917
613,488
JPEG support with ijg - getting access violation
I was recently trying to update my game to store graphics in compressed formats (JPEG and PNG). Whilst I ended up settling on a different library, my initial attempt was to incorporate ijg to do JPEG decompression. However, I was unable to get even the simplest console application to work and am wondering if anyone might be able to shed some light on the reasons why. Here is my code, which is linked to the jpeg.lib that is part of the ijg packages: #include "stdafx.h" #include <stdio.h> #include <assert.h> #include <jpeglib.h> int _tmain(int argc, _TCHAR* argv[]) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buffer; int row_stride; //initialize error handling cinfo.err = jpeg_std_error(&jerr); //initialize the decompression jpeg_create_decompress(&cinfo); FILE* infile; errno_t err = fopen_s(&infile, "..\\Sample.jpg", "rb"); assert(err == 0); //specify the input jpeg_stdio_src(&cinfo, infile); //read headers (void) jpeg_read_header(&cinfo, TRUE); return 0; } The problem is that the call to jpeg_read_header() fails with an access violation: Unhandled exception at 0x7c91b1fa (ntdll.dll) in JPEGTest.exe: 0xC0000005: Access violation writing location 0x00000010. Does anyone have any ideas what I might be doing wrong?
I've just encountered the same problem (although I was trying to encode an image). Apparently, FILE* are not portable between DLLs so you can't use any libjpeg API that takes a FILE* as a parameter. There are several solutions, but they all come down to having to rebuild the library: Build the library as a static lib, and link it to your application. This is what I did, and it solved my problem. Move the source/destination handlers out of libjpeg and into your application. Then you could build libjpeg as either a static lib or a DLL, whichever suits you. I'm not sure whether this would work, but it is the suggested solution in the "install.doc" file distributed with the source code.
392,120
392,138
Why can't I declare a friend through a typedef?
Does anyone know why typedefs of class names don't work like class names for the friend declaration? class A { public: }; class B : public A { public: typedef A SUPERCLASS; }; typedef A X; class C { public: friend class A; // OK friend class X; // fails friend class B::SUPERCLASS; // fails };
It can't, currently. I don't know the reason yet (just looking it up, because i find it interesting). Update: you can find the reason in the first proposal to support typedef-names as friends: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1520.pdf . The reason is that the Standard only supported elaborated-type-specifiers. It's easy to allow only those, and say if the entity declared as friend is not declared yet, it will be made a member of the surrounding namespace. But this means that if you want to use a template parameter, you would have to do (a class is required then for example) friend class T; But that brought additional problems, and it was figured not worth the gain. Now, the paper proposes to allow additional type specifiers to be given (so that this then allows use of template parameters and typedef-names). The next C++ version (due to 2010) will be able to do it. See this updated proposal to the standard: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1791.pdf . It will not allow only typedef names, but also template parameters to be used as the type declared as friend.
392,142
392,148
How would you list the available functions etc contained within a compiled library?
How do I determine whether a function exists within a library, or list out the functions in a compiled library?
You can use the nm command to list the symbols in static libraries. nm -g -C <libMylib.a>
392,359
392,365
How to force a template code creation without creating object instance?
I have a template class that is only valid for couple of template parameters: doIt.h: // only int and float are valid T template <typename T> class doer { public: void doIt(); } I want to hide the implementation inside the .cpp file (for faster compile and also because its proprietary): doIt.cpp: template <> void doer<T>::doIt() { /* how to do it */ } ... and use it as follows: use.cpp: int main( int, char** ) { doer<int>::doIt() } The above fails to link because the implementation of void doer::doIt(void) was never in scope at the place where it was called. I can force the code to be generated into doItv2.obj, as follows: doIt_v2.cpp: template <> void doer<T>::doIt() { /* how to do it */ } doer<int> a; doer<real> b; but this causes a variety of headaches (dynamic memory allocation before main is entered) and I actually don't want to make an instance -- I just want the object code for the template instantiations to be generated. Any ideas?
See the article How to Organize Template Source Code. I think you are after the second method described there: explicit template instantiation.
392,375
392,409
Turn while loop into math equation?
I have two simple while loops in my program that I feel ought to be math equations, but I'm struggling to convert them: float a = someValue; int b = someOtherValue; int c = 0; while (a <= -b / 2) { c--; a += b; } while (a >= b / 2) { c++; a -= b; } This code works as-is, but I feel it could be simplified into math equations. The idea here being that this code is taking an offset (someValue) and adjusting a coordinate (c) to minimize the distance from the center of a tile (of size someOtherValue). Any help would be appreciated.
It can be proved that the following is correct: c = floor((a+b/2)/b) a = a - c*b Note that floor means round down, towards negative infinity: not towards 0. (E.g. floor(-3.1)=-4. The floor() library functions will do this; just be sure not to just cast to int, which will usually round towards 0 instead.) Presumably b is strictly positive, because otherwise neither loop will never terminate: adding b will not make a larger and subtracting b will not make a smaller. With that assumption, we can prove that the above code works. (And paranoidgeek's code is also almost correct, except that it uses a cast to int instead of floor.) Clever way of proving it: The code adds or subtracts multiples of b from a until a is in [-b/2,b/2), which you can view as adding or subtracting integers from a/b until a/b is in [-1/2,1/2), i.e. until (a/b+1/2) (call it x) is in [0,1). As you are only changing it by integers, the value of x does not change mod 1, i.e. it goes to its remainder mod 1, which is x-floor(x). So the effective number of subtractions you make (which is c) is floor(x). Tedious way of proving it: At the end of the first loop, the value of c is the negative of the number of times the loop runs, i.e.: 0 if: a > -b/2 <=> a+b/2 > 0 -1 if: -b/2 ≥ a > -3b/2 <=> 0 ≥ a+b/2 > -b <=> 0 ≥ x > -1 -2 if: -3b/2 ≥ a > -5b/2 <=> -b ≥ a+b/2 > -2b <=> -1 ≥ x > -2 etc., where x = (a+b/2)/b, so c is: 0 if x>0 and "ceiling(x)-1" otherwise. If the first loop ran at all, then it was ≤ -b/2 just before the last time the loop was executed, so it is ≤ -b/2+b now, i.e. ≤ b/2. According as whether it is exactly b/2 or not (i.e., whether x when you started was exactly a non-positive integer or not), the second loop runs exactly 1 time or 0, and c is either ceiling(x) or ceiling(x)-1. So that solves it for the case when the first loop did run. If the first loop didn't run, then the value of c at the end of the second loop is: 0 if: a < b/2 <=> a-b/2 < 0 1 if: b/2 ≤ a < 3b/2 <=> 0 ≤ a-b/2 < b <=> 0 ≤ y < 1 2 if: 3b/2 ≤ a < 5b/2 <=> b ≤ a-b/2 < 2b <=> 1 ≤ y < 2, etc., where y = (a-b/2)/b, so c is: 0 if y<0 and 1+floor(y) otherwise. [And a now is certainly < b/2 and ≥ -b/2.] So you can write an expression for c as: x = (a+b/2)/b y = (a-b/2)/b c = (x≤0)*(ceiling(x) - 1 + (x is integer)) +(y≥0)*(1 + floor(y)) Of course, next you notice that (ceiling(x)-1+(x is integer)) is same as floor(x+1)-1 which is floor(x), and that y is actually x-1, so (1+floor(y))=floor(x), and as for the conditionals: when x≤0, it cannot be that (y≥0), so c is just the first term which is floor(x), when 0 < x < 1, neither of the conditions holds, so c is 0, when 1 ≤ x, then only 0≤y, so c is just the second term which is floor(x) again. So c = floor(x) in all cases.
392,540
392,548
Adding parameters for a program at launch
I'm currently trying to make a small application that performs different duties. Right now I have a console app pop up and ask what I want to do, but sometimes I would rather just launch it with something like MyApp.exe -printdocuments or some such thing. Are there any tutorials out there that can show me a simple example of this?
In C++, your main() function can have argc and argv parameters, which contain the arguments passed on the command line. The argc is the count of arguments (including the executable name itself), and argv is an array of pointers to null-terminated strings of length argc. For example, this program prints its arguments: #include <stdio.h> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("argv[%d]: %s\n", i, argv[i]); } return 0; } Any C or C++ tutorial will probably have more information on this.
392,932
392,946
How do I use the conditional (ternary) operator?
I've always wondered how to write the "A ? B : C" syntax in a C++ compatible language. I think it works something like: (Pseudo code) If A > B C = A Else C = B Will any veteran C++ programmer please help me out?
It works like this: (condition) ? true-clause : false-clause It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in VB, for example). For example: bool Three = SOME_VALUE; int x = Three ? 3 : 0; is the same as bool Three = SOME_VALUE; int x; if (Three) x = 3; else x = 0;
393,241
586,334
Read\write boost::binary_oarchive to pipe
I am continue to build two simple processes throwing class objects one to another (see my previous post) through simple (anonymous) pipes. Now I revealed for myself boost::serialization (thanks answered people) and have tried to make some class be serialized through ::WriteFile::ReadFile. So - what I am doing wrong? 1) I created some class #pragma once #include "wtypes.h" #include <boost\archive\binary_oarchive.hpp> #include <boost\archive\binary_iarchive.hpp> #include <boost\serialization\binary_object.hpp> class CTextContainer { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & m_sText; ar & m_dwCRC; ar & m_dwSize; } public: CTextContainer() : m_dwCRC(0), m_dwSize(0) { ZeroMemory(m_sText, sizeof(m_sText)); m_dwSize = sizeof(*this); } CTextContainer(LPCTSTR sText) : m_dwCRC(0), m_dwSize(0) { ZeroMemory(m_sText, sizeof(m_sText)); wcsncpy_s(m_sText, 1024, sText, wcslen(sText)); m_dwSize = sizeof(*this); } virtual ~CTextContainer(){} LPTSTR GetText() const{return (LPTSTR) m_sText;} protected: DWORD m_dwCRC; DWORD m_dwSize; TCHAR m_sText[1024]; }; //end of class 2) And now I am trying to read from this class into binary archive and to write its content to one end of pipe... boost::archive::binary_oarchive oa(ofs); oa << tc; ::WriteFile(hPipe, &oa, dwRead, &dwWritten, NULL) == FALSE It won't work in that way, right? So, how it will? 3) Same operation on other side?
I think the problem here is that you're trying pass a pointer the the archive object in the WriteFile function. What you should do instead is provide a pointer to serialized data. std::stringstream ss; boost::archive::binary_oarchive oa(ss); oa << tc; ::WriteFile(hPipe, ss.str().data(), ss.str().data().size(), &dwWritten, NULL) As a better alternative you should provide the binary_oarchive constructor with an ostream implementation that writes directly into your file handle.
393,885
393,945
Neatest / Fastest Algorithm for Smallest Positive Number
Simple question - In c++, what's the neatest way of getting which of two numbers (u0 and u1) is the smallest positive number? (that's still efficient) Every way I try it involves big if statements or complicated conditional statements. Thanks, Dan Here's a simple example: bool lowestPositive(int a, int b, int& result) { //checking code result = b; return true; } lowestPositive(5, 6, result);
I prefer clarity over compactness: bool lowestPositive( int a, int b, int& result ) { if (a > 0 && a <= b) // a is positive and smaller than or equal to b result = a; else if (b > 0) // b is positive and either smaller than a or a is negative result = b; else result = a; // at least b is negative, we might not have an answer return result > 0; // zero is not positive }
393,954
395,408
How to convert an OpenCV IplImage to an SDL_Surface?
I'm trying to write a program which takes an SDL_Surface, converts it to an IplImage, uses the cvBlobsLib to find blobs, paints the blobs as spots back over the image, then converts the output IplImage back to an SDL_Surface. I'm almost done: only converting the IplImage back to an SDL_Surface hasn't been done yet. This IplImage has 3 image channels and is 8 bits per pixel. I think I have two calls I can use: SDL_Surface *SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); SDL_Surface *SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); I'm currently trying with SDL_CreateRGBsurfaceFrom. I have no idea, however, what the correct values of pitch, Rmask, Gmask and Bmask are. (Amask is 0, because there is no alpha channel.) Could anybody help me out by explaining how to do this? Thanks! Edit: For example, this is code I tried to use: SDL_Surface *ipl_to_surface (IplImage *opencvimg) { int pitch = opencvimg->nChannels*opencvimg->width; printf("Depth %d, nChannels %d, pitch %d\n", opencvimg->depth, opencvimg->nChannels, pitch); SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)opencvimg->imageData, opencvimg->width, opencvimg->height, opencvimg->depth, pitch, 0x0000ff, 0x00ff00, 0xff0000, 0 ); return surface; } (SDL Documentation writes "Pitch is the size of the scanline of the surface, in bytes, i.e. widthInPixels*bytesPerPixel.") This outputs "Depth 8, nChannels 3, pitch 1920" and displays a completely red image. I think a solution would be to convert my 8-bits image to 24-bits (1 byte per channel), but I don't know how to do that. Any ideas?
Ok, I got it working! I think I was confused by the fact that an OpenCV depth of 8 means a pixel has 8 bits per channel, so in a 3-channel image, a pixel has 24 bits. So when converting that to the SDL meaning of depth, we get 8 * 3 = 24 bits. The image was 24 bits after all, which SDL supports. So converting the image to SDL is as simple as: SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)opencvimg->imageData, opencvimg->width, opencvimg->height, opencvimg->depth*opencvimg->nChannels, opencvimg->widthStep, 0xff0000, 0x00ff00, 0x0000ff, 0 ); return surface; Sorry for the confusion, I hope this helps anybody searching for the same answer. Other links of interest: http://www.libsdl.org/cgi/docwiki.cgi/Pixel_Access And the complete subroutine at: http://paster.dazjorz.com/?p=3714
394,061
394,077
Critical section - to be or not to be?
I`m writing a chat using WinSock2 and WinAPI functions. And I have a little trouble. I store the std::vector of client connections on server. When new client connects, new thread starts and all work with the client is done in this new thread. I do not use classes (I know it is not very good) so this list of connections is just defined as global variable. It seems to me that it can be a situation when several threads try to access this list simultaneously. Though I have not noticed that there are any problems with that, do I need to do something like this: template class SharedVector { std::vector vect; CRITICAL_SECTION cs; SharedVector(const SharedVector& rhs) {} public: SharedVector(); explicit SharedVector(const CRITICAL_SECTION& CS); void PushBack(const T& value); void PopBack(); unsigned int size(); T& operator[](int index); virtual ~SharedVector(); }; template SharedVector::SharedVector() { InitializeCriticalSection(&cs); } template SharedVector::SharedVector(const CRITICAL_SECTION& r): cs(r) { InitializeCriticalSection(&cs); } template void SharedVector::PushBack(const T& value) { EnterCriticalSection(&cs); vect.push_back(value); LeaveCriticalSection(&cs); } template void SharedVector::PopBack() { EnterCriticalSection(&cs); vect.pop_back(); LeaveCriticalSection(&cs); } So, does my situation require using CRITICAL_SECTION and am I just the lucky guy who did not find a mistake?
Yes, you are just lucky never to experience any problems. This is the problem with synchronization issues and race conditions, that the code will work in 99.9% of all cases, and when disaster strikes you won't know why. I would take away the constructor taking a CRITICAL_SECTION as a parameter since it is not clear without looking at (presumably non-existing) documentation to realize that the constructor will initialize it.
394,146
394,156
Displaying polymorphic classes
I have an existing app with a command-line interface that I'm adding a GUI to. One situation that often comes up is that I have a list of objects that inherit from one class, and need to be displayed in a list, but each subclass has a slightly different way of being displayed. Not wanting to have giant switch statements everywhere using reflection/RTTI to do the displaying, each class knows how to return its own summary string which then gets displayed in the list: int position = 0; for (vector<DisplayableObject>::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) cout << ++position << ". " << iDisp->GetSummary(); Similar functions are there to display different information in different contexts. This was all fine and good until we needed to add a GUI. A string is no longer sufficient - I need to create graphical controls. I don't want to have to modify every single class to be able to display it in a GUI - especially since there is at least one more GUI platform we will want to move this to. Is there some kind of technique I can use to separate this GUI code out of the data objects without resorting to RTTI and switch statements? It would be nice to be able to take out the GetSummary functions as well. Ideally I'd be able to have a heierarchy of display classes that could take a data class and display it based on the runtime type instead of the compile time type: shared_ptr<Displayer> displayer = new ConsoleDisplayer(); // or new GUIDisplayer() for (vector<DisplayableObject>::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) displayer->Display(*iDisp);
I don't think this will solve your problem of not needing to write the code, but you should be able to abstract the GUI logic from the data objects. Look at a Visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) it will allow you to add code to an existing object without changing the object itself. You can also change the visitor based on the platform.
394,162
394,182
Fastest way to determine whether a string contains a real or integer value
I'm trying to write a function that is able to determine whether a string contains a real or an integer value. This is the simplest solution I could think of: int containsStringAnInt(char* strg){ for (int i =0; i < strlen(strg); i++) {if (strg[i]=='.') return 0;} return 1; } But this solution is really slow when the string is long... Any optimization suggestions? Any help would really be appreciated!
You are using strlen, which means you are not worried about unicode. In that case why to use strlen or strchr, just check for '\0' (Null char) int containsStringAnInt(char* strg){ for (int i =0;strg[i]!='\0'; i++) { if (strg[i]=='.') return 0;} return 1; } Only one parsing through the string, than parsing through the string in each iteration of the loop.
394,370
394,466
Is it worth learning AMD-specific APIs?
I'm currently learning the APIs related to Intel's parallelization libraries such as TBB, MKL and IPP. I was wondering, though, whether it's also worth looking at AMD's part of the puzzle. Or would that just be a waste of time? (I must confess, I have no clue about AMD's library support - at all - so would appreciate any advice you might have.) Just to clarify, the reason I'm going the Intel way is because 1) the APIs are very nice; and 2) Intel seems to be taking tool support as seriously as API support. (Once again, I have no clue how AMD is doing in this department.)
The MKL and IPP libraries will perform (nearly) as well on AMD machines. My guess is that TBB will also run just fine on AMD boxes. If I had to suggest a technology that would be beneficial and useful to both, it would be to master the OpenMP libraries. The Intel compiler with the OpenMP extensions is stunningly fast and works with AMD chips also.
394,564
394,636
boost::filesystem::path for unicode file paths?
Is there a way to use boost::filesystem::path with unicode file paths? In particular I'd like to use it with std::wstring instead of std::string. I'm working on the windows platform and I need to sometimes process a filepath that has a unicode char in it.
Looking at the header file, I see a wpath that's templated with std::wstring.
394,854
394,867
Silencing GCC warnings when using an "Uncopyable" class
I have several classes that I don't want to be copyable, some of these classes have pointer data members. To make these classes uncopyable I privately inherit the following class template: template <class T> class Uncopyable { protected: Uncopyable() {} virtual ~Uncopyable() {} private: Uncopyable(const Uncopyable &); T & operator=(const T&); }; Which I used like so: class Entity : private Uncopyable<Entity> { } This works fine, however when I compile with -Weffc++ I still get the following warning: class Entity has pointer data members but does not override Entity(const Entity&) or operator=(const Entity&) Why is it still giving me this warning?
C++ says Because a copy assignment operator is implicitly declared for a class if not declared by the user, a base class copy assignment operator is always hidden by the copy assignment operator of a derived class (13.5.3). A using-declaration (7.3.3) that brings in from a base class an assignment operator with a parameter type that could be that of a copy-assignment operator for the derived class is not considered an explicit declaration of a copy-assignment operator and does not suppress the implicit declaration of the derived class copy-assignment operator; the operator introduced by the using-declaration is hidden by the implicitly-declared copy-assignment operator in the derived class. The bug in the code is that your base class declares the operator= to accept a reference of type of the derived class. That won't prevent an implicit public declaration of an operator= for the base. Thus, your derived class and your base class are still assignable. Try changing your noncopyable class into a non-template, which should suffice: class Uncopyable { protected: Uncopyable() {} virtual ~Uncopyable() {} private: Uncopyable(const Uncopyable &); Uncopyable & operator=(const Uncopyable&); }; One more thing i have just figured in that code: Don't make the destructor of Uncopyable virtual. The reason is, no-one (apart from the derived class itself) can call delete on a pointer to Uncopyable (because 1: the destructor is protected, 2: you derive privately). So it's not the concern of Uncopyable to make the destructor of the derived class implicitly virtual. If the derived class needs to have a virtual destructor, put virtual in there instead, and leave Uncopyables' destructor non-virtual.
394,900
395,028
How to write an automated test for thread safety
I have a class which is not thread safe: class Foo { /* Abstract base class, code which is not thread safe */ }; Moreover, if you have foo1 and foo2 objects, you cannot call foo1->someFunc() until foo2->anotherFunc() has returned (this can happen with two threads). This is the situation and it can't be changed (a Foo subclass is actually a wrapper for a python script). In order to prevent unwanted calls I've created the following - class FooWrapper { public: FooWrapper(Foo* foo, FooWrappersMutex* mutex); /* Wrapped functions from Foo */ }; Internally, FooWrapper wraps calls to the Foo functions with the shared mutex. I want to test FooWrapper for thread safety. My biggest problem is the fact that threads are managed by the operating system, which means I've got less control on their execution. What I would like to test is the following scenario: Thread 1 calls fooWrapper1->someFunc() and blocks while inside the function Thread 2 calls fooWrapper2->anotherFunc() and returns immediately (since someFunc() is still executing) Thread 1 finishes the execution What is the simplest to test a scenario like this automatically? I'm using QT on Win32, although I would prefer a solution which is at least cross-platform as QT is.
Instead of just checking that a particular thread is finished or not, why not create a fake Foo to be invoked by your wrapper in which the functions record the time at which they were actually started/completed. Then your yield thread need only wait long enough to be able to distinguish the difference between the recorded times. In your test you can assert that another_func's start time is after some_func's start time and it's completed time is before some_funcs completed time. Since your fake class is only recording the times, this should be sufficient to guarantee that the wrapper class is working properly. EDIT: You know, of course, that what your Foo object does could be an anti-pattern, namely Sequential Coupling. Depending what it does, you may be able to handle it by simply having the second method do nothing if the first method has not yet been called. Using the example from the Sequential Coupling link, this would be similar to having the car do nothing when the accelerator pedal is pressed, if the car has not yet been started. If doing nothing is not appropriate, you could either wait and try again later, initiate the "start sequence" in the current thread, or handle it as an error. All of these things could be enforced by your wrapper as well and would probably be easier to test. You also may need to be careful to make sure that the same method doesn't get invoked twice in sequence if an intervening call to another method is required.
395,060
395,068
Extern keyword and unresolved external symbols
I drew a little graph in paint that explains my problem: But it doesn't seem to show up when I use the <img> tag after posting? Graph:
You need to instantiate the database outside of main(), otherwise you will just declare a local variable shadowing the global one. GameServer.cpp: #include GameSocket.h Database db(1, 2, 3); int main() { //whatever }
395,088
395,143
How to programmatically capture a web page with forced updates
I need to capture a web site and am looking for an appropriate library or program to do this. The website uses Java Script and pushes updates to the page and I need to capture these as well as the page itself. I am using curl to capture the page itself but I don't know how to capture the updates. Where given a choice I would use C++. Regards
Install Firefox and GreaseMonkey. Have the GM script add DOM events where appropriate to track modifications. You can then use XMLHttpRequest to send the information to a server, or write them to local files with XPCOM file IO opearation. With this, you can do what you want in a dozen lines and little to no reverse engineering, whereas what others have advised (screen scraping) will require thousands of lines of code for a JavaScript heavy site IMO. Addenda: this is /not/ a job for C++. And should you do it in C++ anyway, you will end up havin to reverse engineer JS, so you might as well just learn enough JS to use GreaseMonkey in the first place.
395,169
395,216
Using CMake to generate Visual Studio C++ project files
I am working on an open source C++ project, for code that compiles on Linux and Windows. I use CMake to build the code on Linux. For ease of development setup and political reasons, I must stick to Visual Studio project files/editor on Windows (I can't switch to Code::Blocks, for example). I see instructions to generate Visual Studio files using CMake, as here. Have you used CMake to generate Visual Studio files before? How has been your experience? Suppose I want to add a new file to my project. What is the workflow for this?
CMake is actually pretty good for this. The key part was everyone on the Windows side has to remember to run CMake before loading in the solution, and everyone on our Mac side would have to remember to run it before make. The hardest part was as a Windows developer making sure your structural changes were in the cmakelist.txt file and not in the solution or project files as those changes would probably get lost and even if not lost would not get transferred over to the Mac side who also needed them, and the Mac guys would need to remember not to modify the make file for the same reasons. It just requires a little thought and patience, but there will be mistakes at first. But if you are using continuous integration on both sides then these will get shook out early, and people will eventually get in the habit.
395,685
395,738
How do you choose between a singleton and an unnamed class?
I'd use a singleton like this: Singleton* single = Singleton::instance(); single->do_it(); I'd use an unnamed class like this: single.do_it(); I feel as if the Singleton pattern has no advantage over the unnamed class other than having readable error messages. Using singletons is clumsier than using an unnamed class object: First, clients must first get a handle of the instance; second, the implementer of Singleton::instance() might need to consider concurrency. So why and how would you choose a singleton over an unnamed class? As an addendum, although the obvious definition of an unnamed class might be class { // ... }single; I could as well define it like so: #ifndef NDEBUG class Singleton__ { // readable error messages, #else class { // unnamed, clients can't instantiate #endif // ... }single; with the latter approach having the advantage of readable compiler error messages but not being a singleton in debug mode.
I think the most important reason is that you cannot put an unnamed class in namespace scope. So, the following is not valid (gcc accepts, but warns. comeau doesn't accept in strict mode): class { } single; int main() { } The type of single has no linkage because there is no way to declare its name in another scope referring to it (precisely because it has no name). But using it to declare single, which has linkage (external here) is not valid (3.5/8). single has to be defined locally in main where it will have no linkage. You also cannot pass single to function templates and it can't have static data members (because there is no way to define them). All those restrictions make it more or less not applicable as a substitution for a singleton.
395,877
395,883
Are child processes created with fork() automatically killed when the parent is killed?
I'm creating child processes with fork() in C/C++. When the parent process ends (or is killed for some reason) I want all child processes to be killed as well. Is that done automatically by the system? Or I have to do it myself? Pre-existing similar questions: How can I cause a child process to exit when the parent does? How to make child process die after parent exits?
No. If the parent is killed, children become children of the init process (that has the process id 1 and is launched as the first user process by the kernel). The init process checks periodically for new children, and waits for them (thus freeing resources that are allocated by their return value). The question was already discussed with quality answers here: How to make child process die after parent exits?
395,990
396,034
Is it Wise to Spend Cash on a C++ Book Keeping in View the Upcoming C++0x?
I just purchased C++ GUI Programming with Qt4 and after reading the code samples in this book I'm beginning to realize that my knowledge of C++ is incomplete. I learned C++ two years ago from online tutorials and a couple of ebooks I downloaded, and it turns out none of these resources were good enough. Since then I haven't touched the language and have been using Python instead. Now I'm thinking of purchasing a good book on C++ that covers advanced topics, and the one I have in mind is Bruce Eckel's Thinking in C++ (both volumes). I know they are available for free on the web, but I really can't stand reading books on a laptop screen. Since C++0x might be out pretty soon, is it wise to go ahead and spend cash on these books? Will C++0x break backwards compatibility? Volume 2 covers features like multithreading, templates etc. Would any of these features change significantly in C++0x?
I wouldn't hold my breath for C++0x. I doubt it will be out by the end of this decade. Even when it will be out, you should probably count a year or so for compilers to implement it. Learn the fundamentals now, and it should be relatively easy for you to learn most of the new features when the standard is out. The Standards Committee is known for its efforts to maintain backward compatibility. I personally check with the evolution of the standard from time to time, just out of curiosity. Subscribe to Herb Sutter's blog feed and look for Standard updates. My personal favourite advanced C++ book is Bjarne Stroustrup's The C++ Programming Language, 3e. It is the one single C++ book from which I think I learnt the most, with respect to language and STL details. Scott Meyers' books helped clarify a lot of things too. Meyers writes in a very readable language (English, I believe), and often what would happen is that I'd read an entire Item from Meyers' book, and then find the same information in Stroustrup's book condensed into a single sentence or so. That is to say Meyers' books are extremely useful in getting your attention to interesting details. As for the changes I expect for threading, I think there going to be two new libraries for this purpose in the standard. Concepts are an even bigger change coming, and they are somewhat related to templates. Up until now we had concepts in the STL, but these were conventions; an algorithm would make assumptions about a type you pass to a template, and you'd know to pass the correct "type of type" because of the conventions. This implied terribly error messages, the STL template errors we all know and "love". Concepts will help solve these. There are other improvements (complexities) to the language. Herb Sutter talks about them a lot.
396,084
396,094
Headers Including Each Other in C++
I'm a C++ newbie, but I wasn't able to find the answer to this (most likely trivial) question online. I am having some trouble compiling some code where two classes include each other. To begin, should my #include statements go inside or outside of my macros? In practice, this hasn't seemed to matter. However, in this particular case, I am having trouble. Putting the #include statements outside of the macros causes the compiler to recurse and gives me "#include nested too deeply" errors. This seems to makes sense to me since neither class has been fully defined before #include has been invoked. However, strangely, when I try to put them inside, I am unable to declare a type of one of the classes, for it is not recognized. Here is, in essence, what I'm trying to compile: A.h #ifndef A_H_ #define A_H_ #include "B.h" class A { private: B b; public: A() : b(*this) {} }; #endif /*A_H_*/ B.h #ifndef B_H_ #define B_H_ #include "A.h" class B { private: A& a; public: B(A& a) : a(a) {} }; #endif /*B_H_*/ main.cpp #include "A.h" int main() { A a; } If it makes a difference, I am using g++ 4.3.2. And just to be clear, in general, where should #include statements go? I have always seen them go outside of the macros, but the scenario I described clearly seems to break this principle. Thanks to any helpers in advance! Please allow me to clarify my intent if I have made any silly mistakes!
By "the macros" I assume you mean the #ifndef include guards? If so, #includes should definitely go inside. This is one of the major reasons why include guards exists, because otherwise you easily end up with an infinite recursion as you noticed. Anyway, the problem is that at the time you use the A and B classes (inside the other class), they have not yet been declared. Look at what the code looks like after the #includes have been processed: //#include "A.h" start #ifndef A_H_ #define A_H_ //#include "B.h" start #ifndef B_H_ #define B_H_ //#include "A.h" start #ifndef A_H_ // A_H_ is already defined, so the contents of the file are skipped at this point #endif /*A_H_*/ //#include "A.h" end class B { private: A& a; public: B(A& a) : a(a) {} }; #endif /*B_H_*/ //#include "B.h" end class A { private: B b; public: A() : b(*this) {} }; #endif /*A_H_*/ //#include "A.h" end int main() { A a; } Now read the code. B is the first class the compiler encounters, and it includes an A& member. What is A? The compiler hasn't encountered any definition of A yet, so it issues an error. The solution is to make a forward declaration of A. At some point before the definition of B, add a line class A; This gives the compiler the necessary information, that A is a class. We don't know anything else about it yet, but since B only needs to include a reference to it, this is good enough. In the definition of A, we need a member of type B (not a reference), so here the entire definition of B has to be visible. Which it is, luckily.
396,100
396,105
What is the best way to check for memory leaks in c++?
I'm implementing a sparse matrix with linked lists and it's not fun to manually check for leaks, any thoughts?
The valgrind profiler for Unix offers a decent leak detection. However, this is only one part of a successful approach. The other part is to prevent (i.e. minimize) explicit memory handling. Smart pointers and allocators can help a great deal in preventing memory leaks. Also, do use the STL classes: a leak-free linked list implementation is already provided by std::list.
396,183
396,308
How do you get a minimal SDL program to compile and link in visual studio 2008 express?
I'm trying to use SDL in C++ with Visual Studio 2008 Express. The following program compiles but does not link: #include <SDL.h> int main(int argc, char *argv[]) { return 0; } The link error is: LINK : fatal error LNK1561: entry point must be defined I get this regardless of how or if I link with SDL.lib and SDLmain.lib. Defining main as main() or SDL_main() gives the same error, with or without extern "C". Edit: I solved this by not including SDL.h in main.cpp - a refactoring I did independent of the problem. A similar solution would be to #undef main right before defining the function.
I don't have VC++ available at the moment, but I have seen this issue several times. You need to create a Win32 project as opposed to a console project. A Win32 project expects a WinMain function as a program entry point. SDLmain.lib contains this entry point and the SDL_main.h header file has a macro that remaps your main function to SDL_main. This function is called by the entry point in the SDLmain library. The main function must have the following signature: int main(int argc, char *argv[]) It is also required to include SDL.h before the declaration of your main function, and you need to link to both SDL.lib and SDLmain.lib. It looks like you are doing this. So, my guess is that you have a console project setup. Therefore, the linker is looking for a main function to call, but it is getting remapped to SDL_main by the macro SDL_main.h. So, the linker can't find an entry point and gives up!
396,327
396,353
Question on multiple inheritance, virtual base classes, and object size in C++
The following code prints 20, i.e. sizeof(z) is 20. #include <iostream.h> class Base { public: int a; }; class X:virtual public Base { public: int x; }; class Y:virtual public Base { public: int y; }; class Z:public X,public Y { }; int main() { Z z; cout << sizeof(z) <<endl; } Whereas if I don't use virtual base classes here, i.e. for the following code : sizeof(z) is 16. #include <iostream.h> class Base { public: int a; }; class X:public Base { public: int x; }; class Y:public Base { public: int y; }; class Z:public X,public Y { }; int main() { Z z; cout << sizeof(z) <<endl; } Why is sizeof(z) more(20) in the first case? Shouldn't it be 12, since Base will be included only once in Z?
Let's look at the class layout of the two cases. Without the virtual, you have two base classes ("X" and "Y") with an integer each, and each of those classes have integrated into them a "Base" base class which also has an integer. That is 4 integers, 32-bits each, totalling your 16 bytes. Offset Size Type Scope Name 0 4 int Base a 4 4 int X x 8 4 int Base a 12 4 int Y y 16 size (Z members would come at the end) (Edit: I've written a program in DJGPP to get the layout and tweaked the table to account for it.) Now let's talk about virtual base classes: they replace the actual instance of the class with a pointer to a shared instance. Your "Z" class has only one "Base" class, and both instances of "X" and "Y" point to it. Therefore, you have integers in X, Y, and Z, but you only have the one Z. That means you have three integers, or 12 bytes. But X and Y also have a pointer to the shared Z (otherwise they wouldn't know where to find it). On a 32-bit machine two pointers will add an additional 8 bytes. This totals the 20 that you see. The memory layout might look something like this (I haven't verified it... the ARM has an example where the ordering is X, Y, Z, then Base): Offset Size Type Scope Name Value (sort of) 0 4 Base offset X ? 16 (or ptr to vtable) 4 4 int X x 8 4 Base offset Y ? 16 (or ptr to vtable) 12 4 int Y y 16 4 int Base a 20 size (Z members would come before the Base) So the memory difference is a combination of two things: one less integer and two more pointers. Contrary to another answer, I don't believe vtables pay any (edit) direct (/edit) roll in this, since there are no virtual functions. Edit: ppinsider has provided more information on the gcc case, in which he demonstrates that gcc implements the pointer to the virtual base class by making use of an otherwise empty vtable (i.e., no virtual functions). That way, if there were virtual functions, it wouldn't require an additional pointer in the class instance, requiring more memory. I suspect the downside is an additional indirection to get to the base class. We might expect all compilers to do this, but perhaps not. The ARM page 225 discusses virtual base classes without mentioning vtables. Page 235 specifically addresses "virtual base classes with virtual functions" and has a diagram indicating a memory layout where there are pointers from the X and Y parts that are separate from the pointers to the vtable. I would advise anyone not to take for granted that the pointer to Base will be implemented in terms of a table.
396,579
396,808
How can I create cells or grids in C++ for a randomized maze?
I'm trying to create a randomized maze in C++, but I can't start because I don't know how to create grids or cells. How could I create it? And I also want to create it using ASCII characters. how can i store it in array? (can any one give a sample code and some explanation so i can understand it better) Another question: What data stuctures should I need to learn and use? I'm planning to use Eller's algorithm or Kruskal's algorithm. Thank you guys for helping me! im a begginer programmer, and i want to learn about this, because this is a part of my project, thank you vary much!
You probably want to store your maze in a 2-dimension char array. You can declare an array with or without initializing it in C++. char a[30][10]; // declares a char array of 30 rows and 10 columns. // declare an array with 3 rows and 3 columns, and provide initial values char ticTacToeBoard[3][3] = {{'x', 'x', 'o'}, {'o', 'o', 'x'}, {'x', 'o', ' '} }; You could change the initial values to '|' and '-' for walls in your maze, and use a space character, ' ', for the passageways. Either initialization method works, but you always use the elements the same way. Here's how you clear the board in the initialized array above. // clear the board for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { ticTacToeBoard[row][col] = ' '; } } If you want to read the value of an element (useful when you're trying to navigate a maze), you use the same subscript notation as when you're setting its value. char y = a[2][2]; // reads the character in row 2, column 2
396,923
396,936
FastCGI request handling
The docs at www.fastcgi.com aren't clear on this (to me), so I hope someone can give me a definitive answer. I have written a FastCGI application in C++ to do some heavy duty number crunching. When the application first loads (when apache starts), it performs some caching of MySQL data into a vector, which takes about a minute (hence using FastCGI instead of CGI ;-)). Then it waits for a request to kick off the number crunching. Normally, a user makes the request, the FastCGI app runs no problem, and returns the correct data. However, I am not sure what is happening when there are several requests initiated at about the same time. Does FastCGI queue those requests, and wait for the previous run to finish before responding to the next request? Or does FastCGI handle the requests in parallel? Can this be configured, and do you configure it in your application or in the apache configs? What's the default? My application only implements while(FCGX_Accept( &in, &out, &err, &envp)>=0){} and performs the number crunching inside the while loop. Appreciate any help, cheers bros.
Looking at my web server, I only have one of each FastCGI process running at any one time, no matter how many Apache instances are running. So I have to assume it's queuing them up.
397,064
397,177
calling code stored in the heap from vc++
Imagine I am doing something like this: void *p = malloc (1000); *((char*)p) = some_opcode; *((char*)p+1) = another_opcode; // for the sake of the example: the opcodes are ok .... etc... How can I define a function pointer to call p as if it was a function? (i'm using VC++ 2008 express). Thanks
A comment wasn't enough space. Joe_Muc is correct. You should not stuff code into memory obtained by malloc or new. You will run into problems if you change the page properties of pages that Windows allocates. This isn't a problem becuase using VirtualAlloc() and the related WIn32 APIs is every easy: call VirtualAlloc() and set the flProtect to [PAGE_EXECUTE_READWRITE][2] Note, you should probably do three allocations, one guard page, the pages you need for your code, then another guard page. This will give you a little protection from bad code. Also wrap calls to your generated code with structured exception handling. Next, the Windows X86 ABI (calling conventions) are not well documented (I know, I've looked). There is some info here, here, here The best way to see how things work is to look at code generated by the compiler. This is easy to do with the \FA switches ( there are four of them). You can find the 64-bit calling conventions here. Also, you can still obtain Microsoft's Macro Assembler MASM here. I recommend writing your machine code in MASM and look at its output, then have your machine code generator do similar things. Intel's and AMD's processor manuals are good references - get them if you don't have them.
397,128
397,146
sending commands to an application from Excel? COM?
I wrote a device controller (rs232) and it is being used successfully, however users want to view data and control the device (or perhaps communicate through my program) from Excel. I dismissed DDE as an option and found that RTD (IRtdServer) is probably a good start (though no way to send data back to the "server" from the real time data client). I found these resources for the RTD part: http://support.microsoft.com/?id=327215 and http://support.microsoft.com/?id=327215 This is a multi-threaded app and I had already added the ability to have multiple listeners on the com port so that I could update multiple clients. I will add the COM interface to the EXE. But what I need after that is some way of controlling my app/proxying commands to the device through my app from Excel. What would be the best way to do that? Perhaps another COM interface and calling it from VBA or something? I am not familiar with using scripting from Excel, so perhaps someone can provice sample code or links that show both the code for a COM object and the accompanying VB(A?) code? Keep in mind that this is an unmanaged C++ application and it cannot be converted to managed or C# right now. Alternatives using C# are welcome as well, but that is a long-term rewrite. Thanks EDIT I have an alternative to adding COM support into the existing EXE. I think it is more flexible to add a two-way communications (cross platform - maybe boost or corba or just straight IP based with my own message protocol) A COM server (or two) can wrap that communications channel - whatever it is. This doesn;t really affect my question at all - I still would like to know the options for controlling an external EXE from Excel. EDIT Not having to roll out .NET to customers is also an big plus. many of these devices are on PCs that are pretty old and have perhaps NT or XP on them and I don't relish increasing my setup/install package from 700KB to the ridiculous .NET install size...
Option #1: Create a small COM server - make sure its interfaces are suitable for scripting with the built Visual Basic engine in Excel. (e.g. use simple types and BSTRS). Write Excel VB Macros to (1) add your own tool bar to excel and (2) call your COM server. You can also add buttons and other UI elements to sheets and hook them them up to VB macros. Option #2: I realize that you do not want to use C# - but automating office, and talking to COM objects is really, really easy in C# with Visual Studio Tools for Office (VSTO). You shoul really look into this option - If done correctly, it shouldn't mean re-writing any of your existing code. Just use C# and VSTO as a bridge between Excel and your RTD server. As with VB, its straight froward to connect UI elements in Excel to C# and then to your RTD server.
397,263
397,267
When to use pointers and when not to?
I'm used to doing Java programming, where you never really have to think about pointers when programming. However, at the moment I'm writing a program in C++. When making classes that have members of other classes, when should I use pointers and when should I not? For example, when would I want to do this: class Foo { Bar b; } As opposed to this: class Foo { Bar* b; }
Start by avoiding pointers. Use them when: You want to use the Pimpl idiom, or an abstract factory. The Bar instance is actually managed by some other part of your program, whereas the Foo class just needs to be able to access it. You want to postpone the construction of the Bar object (i.e., you want to create it after constructing Foo). In your business logic, the Bar object may not exist at all; you would use null also in Java. However, check out boost::optional as well. Bar is actually a base class, and you need the instance to be polymorphic. You happen to be using a toolkit that prefers to present GUI widgets as pointers. Examples could include (but are certainly not limited to) wxWidgets and GLUI. In any of these cases (*), start by using a smart pointer, such as boost::shared_ptr. Otherwise, you are likely to forget to deallocate the memory, sooner or later. Once you know what you are doing, consider case-by-case what pointer type is best. (*) any case – except, probably, the bullet regarding GUI widgets; in this case, your toolkit would most probably manage the resources for you as well
397,404
397,409
virtual function call from base class
Say we have: Class Base { virtual void f(){g();}; virtual void g(){//Do some Base related code;} }; Class Derived : public Base { virtual void f(){Base::f();}; virtual void g(){//Do some Derived related code}; }; int main() { Base *pBase = new Derived; pBase->f(); return 0; } Which g() will be called from Base::f()? Base::g() or Derived::g()? Thanks...
The g of the derived class will be called. If you want to call the function in the base, call Base::g(); instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement: virtual void g() { Base::g(); // some work related to derived } The fact that a function from the base can call a virtual method and control is transferred into the derived class is used in the template method design pattern. For C++, it's better known as Non-Virtual-Interface. It's widely used also in the C++ standard library (C++ stream buffers for example have functions pub... that call virtual functions that do the real work. For example pubseekoff calls the protected seekoff). I wrote an example of that in this answer: How do you validate an object’s internal state?
397,420
399,249
Can any one provide me a sample of using CreateHatchBrush
I want to draw a shadow around a thumbnail in my software. It seems CreateHatchBrush can help but I do not know how to use it, can anyone provide me a sample in C++? Many thanks!
The easiest option would be to use GDI+ to do this. Here's a quick and dirty shadow rendering sample: void Render( HDC hdc ) { Graphics gr( hdc ); Image image( L"sample.jpg" ); const int SHADOW_OFFSET = 7; // // draw shadow // SolidBrush shadow( Color( 190, 190, 190 ) ); Rect rc( 50, 50, image.GetWidth(), image.GetHeight() ); rc.Offset( SHADOW_OFFSET, SHADOW_OFFSET ); gr.FillRectangle( &shadow, rc ); // // draw the image // gr.DrawImage( &image, 50, 50, image.GetWidth(), image.GetHeight() ); // // draw a border // Pen border( Color( 0, 0, 0 ), 1 ); rc.Offset( -SHADOW_OFFSET, -SHADOW_OFFSET ); gr.DrawRectangle( &border, rc ); } Hope this helps!
397,483
397,503
C++ associative array with arbitrary types for values
What is the best way to have an associative array with arbitrary value types for each key in C++? Currently my plan is to create a "value" class with member variables of the types I will be expecting. For example: class Value { int iValue; Value(int v) { iValue = v; } std::string sValue; Value(std::string v) { sValue = v; } SomeClass *cValue; Value(SomeClass *v) { cValue = c; } }; std::map<std::string, Value> table; A downside with this is you have to know the type when accessing the "Value". i.e.: table["something"] = Value(5); SomeClass *s = table["something"].cValue; // broken pointer Also the more types that are put in Value, the more bloated the array will be. Any better suggestions?
boost::variant seems exactly what you are looking for.
397,895
397,969
How could I create a list in c++?
How can I create a list in C++? I need it to create a linked list. How would I go about doing that? Are there good tutorials or examples I could follow?
I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it. First, read Why do we use arrays instead of other data structures? , which contains a good answer of basic data-structures. Then think about how to model them in C++: struct Node { int data; Node * next; }; Basically that's all you need to implement a list! (a very simple one). Yet it has no abstractions, you have to link the items per hand: Node a={1}, b={20, &a}, c={35, &b} d={42, &c}; Now, you have have a linked list of nodes, all allocated on the stack: d -> c -> b -> a 42 35 20 1 Next step is to write a wrapper class List that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified): class List { struct Node { int data; Node * next; }; Node * head; public: List() { head = NULL; } ~List() { while(head != NULL) { Node * n = head->next; delete head; head = n; } } void add(int value) { Node * n = new Node; n->data = value; n->next = head; head = n; } // ... }; Next step is to make the List a template, so that you can stuff other values (not only integers). If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.
398,069
398,126
Static member variable in template, with multiple dlls
My code is built to multiple .dll files, and I have a template class that has a static member variable. I want the same instance of this static member variable to be available in all dlls, but it doesn't work: I see different instance (different value) in each of them. When I don't use templates, there is no problem: initialize the static member in one of the source files, and use __declspec(dllexport) and __declspec(dllimport) directives on the class. But it doesn't work with templates. Is there any way to make it work? I saw some proposed solutions that use "extern", but I think I can't use it because my code is supposed to work with visual studio 2002 and 2005. Thank you. Clarification: I want to have a different instance of static variable per each different type of template instantiation. But if I instantiate the template with the same type in 2 different dlls, I want to have the same variable in the both of them.
Create template specialization and then export the static members of the specialization.
398,543
398,656
Passing newly allocated data directly to a function
While learning different languages, I've often seen objects allocated on the fly, most often in Java and C#, like this: functionCall(new className(initializers)); I understand that this is perfectly legal in memory-managed languages, but can this technique be used in C++ without causing a memory leak?
Your code is valid (assuming functionCall() actually guarantees that the pointer gets deleted), but it's fragile and will make alarm bells go off in the heads of most C++ programmers. There are multiple problems with your code: First and foremost, who owns the pointer? Who is responsible for freeing it? The calling code can't do it, because you don't store the pointer. That means the called function must do it, but that's not clear to someone looking at that function. Similarly, if I call the code from somewhere else, I certainly don't expect the function to call delete on the pointer I passed to it! If we make your example slightly more complex, it can leak memory, even if the called function calls delete. Say it looks like this: functionCall(new className(initializers), new className(initializers)); Imagine that the first one is allocated successfully, but the second one throws an exception (maybe it's out of memory, or maybe the class constructor threw an exception). functionCall never gets called then, and can't free the memory. The simple (but still messy) solution is to allocate memory first, and store the pointer, and then free it in the same scope as it was declared (so the calling function owns the memory): className* p = new className(initializers); functionCall(p); delete p; But this is still a mess. What if functionCall throws an exception? Then p won't be deleted. Unless we add a try/catch around the whole thing, but sheesh, that's messy. What if the function gets a bit more complex, and may return after functionCall but before delete? Whoops, memory leak. Impossible to maintain. Bad code. So one of the nice solutions is to use a smart pointer: boost::shared_ptr<className> p = boost::shared_ptr<className>(new className(initializers)); functionCall(p); Now ownership of the memory is dealt with. The shared_ptr owns the memory, and guarantees that it'll get freed. We could use std::auto_ptr instead, of course, but shared_ptr implements the semantics you'd usually expect. Note that I still allocated the memory on a separate line, because the problem with making multiple allocations on the same line as you make the function call still exists. One of them may still throw, and then you've leaked memory. Smart pointers are generally the absolute minimum you need to handle memory management. But often, the nice solution is to write your own RAII class. className should be allocated on the stack, and in its constructor, make what allocations with new are necessary. And in its destructor, it should free that memory. This way, you're guaranteed that no memory leaks will occur, and you can make the function call as simple as this: functionCall(className(initializers)); The C++ standard library works like this. std::vector is one example. You'd never allocate a vector with new. You allocate it on the stack, and let it deal with its memory allocations internally.
398,641
399,612
Trouble with Factory and dynamic allocation in C++
I have a factory that builds the objects with longest lifetime in my application. These have types, lets say, ClientA and ClientB, which depend on Provider (an abstract class with many possible implementations), so both clients have a reference to Provider as member. According to the command-line arguments, the factory chooses one implementation of Provider, constructs it (with "new"), and passes it to the constructors of both clients. The factory returns an object that represents my entire app. My main function is basically this: int main(int argc, char** argv) { AppFactory factory(argc, argv); App app = factory.buildApp(); return app.run(); } And the buildApp method is basically this: App AppFactory::buildApp() { Provider* provider = NULL; if (some condition) { provider = new ProviderX(); } else { provider = new ProviderY(); } ClientA clientA(*provider); ClientB clientB(*provider); App app(clientA, clientB); return app; } So, when execution ends, destructors of all objects are called, except for the provider object (because it was constructed with "new"). How can I improve this design to make sure that the destructor of the provider is called? EDIT: To clarify, my intention is that both clients, the provider and the App object to share the same lifetime. After all answers, I now think both clients and the provider should be allocated on the heap its references passed to the App object, which will be responsible for deleting them when it dies. What do you say?
It's very simple with a shared ownership smart pointer: App AppFactory::buildApp() { boost::shared_ptr<Provider> provider; if (some condition) { provider.reset(new ProviderX()); } else { provider.reset(new ProviderY()); } ClientA clientA(provider); ClientB clientB(provider); App app(clientA, clientB); return app; } Assuming the app object owns the clients, and the clients all share the one provider. Make the clients take a shared_ptr<Provider> then, instead of a Provider& . As long as there is still a copy of a shared_ptr owning the provider object, the object won't be freed. The best would be to not copy clientA and clientB, and not copy app by returning it by value, but move the clients into the app, and move the app itself into the returned object. That will be possible with the upcoming C++ version. But currently, either you make them pointers (using shared_ptr), or you keep copying them. Another option would be to use auto_ptr, which has a pseudo-transfer-of-ownership semantic. But that template has some inherent problems. So you should avoid using it.
398,682
398,742
Finding statement pattern in c++ file
I have a macro that looks like this: #define coutError if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods() where ods() is a class that behaves similarly to cout, and VERBOSITY_SETTING is a global variable. There are a few of these for different verbosity settings, and it allows the code to look something like this: if (someErrorCondition) { // ... do things relating to the error condition ... coutError << "Error condition occurred"; } And there is functionality in this framework to set the verbosity, etc. However, the obvious pattern breaks when not using braces in something like this: void LightSwitch::TurnOn() { if (!PowerToSwitch) coutError << "No power!"; else SwitchOn = true; } because of the macro, will turn into this: void LightSwitch::TurnOn() { if (!PowerToSwitch) if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods() << "No power!"; else SwitchOn = true; } Which is not the intended functionality of the if statement. Now, I understand a way to fix this macro properly so it doesn't cause this problem, but I'd like to run an audit on the code and find any place that has this pattern of "if (...) coutError << ...; else" to find out if there are any other cases where this happens to make sure that when fixing the macro, it will indeed be correct functionality. I can use any language/tool to find this, I just want to know the best way of doing that.
You could try - temporarily - modifying the macro to something like this, and see what doesn't compile... #define coutError {} if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods() The 'else' clauses should now give errors.
398,888
398,911
Extending a C++ application with C# plugins
I have a C++ Windows application that can be extended by writing C++ plugins, using an API that is exposed by the application. There is also one plugin that translates the C++ API to Python (e.g. plugins can be written in Python). I want to allow users to write plugins in C# in addition to C++ and Python. Since I'm not very familiar with the .NET world, I'm not sure how to implement the C# plugin system. What would you recommend to use for this kind of plugin system (host is C++, plugins in C#)? What do I need to learn in order to achieve this?
There are a couple of prior posts that may help you out: Interfacing using a simple API Communicating between C++ and C# via DLL interface
399,003
399,030
Is the sizeof(some pointer) always equal to four?
For example: sizeof(char*) returns 4. As does int*, long long*, everything that I've tried. Are there any exceptions to this?
The guarantee you get is that sizeof(char) == 1. There are no other guarantees, including no guarantee that sizeof(int *) == sizeof(double *). In practice, pointers will be size 2 on a 16-bit system (if you can find one), 4 on a 32-bit system, and 8 on a 64-bit system, but there's nothing to be gained in relying on a given size.
399,304
399,322
Store huge std::map, mostly on disk
I've got a C++ program that's likely to generate a HUGE amount of data -- billions of binary records of varying sizes, most probably less than 256 bytes but a few stretching to several K. Most of the records will seldom be looked at by the program after they're created, but some will be accessed and modified regularly. There's no way to tell which are which when they're created. Considering the volume of data, there's no way I can store it all in memory. But as the data only needs to be indexed and accessed by its number (a 64-bit integer), I don't want the overhead of a full-fledged database program. Ideally I'd like to treat it as an std::map with its data stored on disk until requested. Is there an already-written library that will do what I'm looking for, or do I need to write it myself? EDIT: After some thought, I realized that Rob Walker's answer had a valid point: I'd be hard-pressed to get anywhere near the same kind of data integrity out of a home-brew class that I'd get from a real database. Although BerkeleyDB (as suggested by RHM) looks like it would do exactly what we're looking for, the dual-licensing is a headache that we don't want to deal with. When we're done with the code and can prove that it would benefit noticeably from BerkeleyDB (which it probably would), we'll reexamine the issue. I did look at Ferruccio's suggestion of stxxl, but I wasn't able to tell how it would handle the program being interrupted and restarted (maybe with changes). With that much data, I'd hate to just scrap what it had already completed and start over every time, if some of the data could be saved. So we've decided to use an SQLite database, at least for the initial development. Thanks to everyone who answered or voted.
I doubt you will find a library that meets your requirements exactly, so you'll have to decide on what 'features' are really important to you and then decide if an existing DB solution comes close enough. Billions of records is a large dataset by any stretch. What rate are records generated at? How long do they persist? Does the access pattern change over time? Are updates always with the same amount of data as the original? I would suggest proving definitively that a DB solution isn't going to work before starting to roll your own, particularly if integrity of the data is paramount (and it usually is...) Maintaining that volume of data on disk reliably can definitely be a challenge. Do you need any kind of transaction semantics when changing the data? Is the client multithreaded?
399,452
399,682
Forward declare method pointer
I am using the pimpl idiom and want to reference one of the methods of the forward declared class. Below isn't exactly what I'm doing but uses the same concepts. template< typename Class, void (Class::*Method)(void) > struct Call { Call( Class* c ) : m_c(c) { } void operator()( void ) { (m_c->*Method)(); } Class* m_c; }; class A { public: void foo( void ) { std::cout << "A::foo\n"; } }; // this works void do_foo( A* a ) { Call<A,&A::foo> c(a); c(); } class B; // this doesn't compile extern void B::bar( void ); // this is what i'd ultimately like to do void do_bar( B* b ) { Call<B,&B::bar> c(b); c(); } Two questions: Can this be done? Why can't it be done?
You cannot forward declare a member function. I think the reason is that, when you call the function on a pointer to B, the compiler has to pass the this pointer to that method. But it doesn't know the precise class hierarchy of B yet. So possible adjustments of that pointer (due to the method being virtual, for example) would not be possible at that point. The compiler would also not know what visibility that method has. After all, it could be private and you are not allowed to call it from outside. The only way to declare that member function is to define the class, and then declare the function within that definition. Another way to solve your problem is to declare your free function instead: class B; void do_bar( B* b ); Then define do_bar in a file in which you can safely include the definition of the class B.
399,538
399,668
How do I link PDCurses to a C++ application on Windows?
I'm building a C++ application and need to use PDCurses on Windows. I'm compiling with VC++ from MS VS 2005 and I'm getting a link error. error LNK2019: unresolved external symbol __imp__GetKeyState@4 referenced in function __get_key_count There are 11 errors all with the same error code and different symbols. The missing symbols are __imp__MapVirtualKeyA@8, __imp__FindWindowA@8, __imp__wsprintfA, __imp__SendMessageA@16, __imp__GetWindowThreadProcessId@8, __imp__MessageBeep@4. It is almost like the VC++ can't find the appropriate ASCII implementations of these functions. I should also note that the demo programs that come with PDCurses compiled fine, though they are C programs. In the C++ program, I include the header using extern "C" { #include <curses.h> } I'm sure I'm forgetting to link against some C standard library, but I'm not sure which one.
GetKeyState() is a Windows function in "user32.dll", so you need to be sure you're linking against "user32.lib". You may also need to make sure it comes after the PDCurses library in the list of linker libraries, too.
399,740
399,742
Design question for abstract base class?
Have a interface class abc { public: virtual int foo() = 0; ... } class concrete1: public abc { public: int foo() { .. } class concrete2 : public abc { public: int foo() { .. } } Now in my main program I need to construct classes based upon a value of a variable abc *a; if (var == 1) a = new concrete1(); else a = new concrete2(); Obviously I don't want these two lines everywhere in the program (please note I have simplified here so that things are clear). What design pattern should I be using if there are any?
You are looking for http://en.wikipedia.org/wiki/Factory_method_pattern
399,792
399,819
Inadvertent use of = instead of ==
It seems that if (x=y) { .... } instead of if (x==y) { ... } is a root of many evils. Why don't all compilers mark it as error instead of a configurable warning? I'm interested in finding out cases where the construct if (x=y) is useful.
Most of the time, compilers try very hard to remain backward compatible. Changing their behavior in this matter to throw errors will break existing legitimate code, and even starting to throw warnings about it will cause problems with automatic systems that keep track of code by automatically compiling it and checking for errors and warnings. This is an evil we're pretty much stuck with at the moment, but there are ways to circumvent and reduce the dangers of it. Example: void *ptr = calloc(1, sizeof(array)); if (NULL = ptr) { // Some error } This causes a compilation error.
399,907
399,915
Pointer class assistance
I'm writing a sparse matrix class in C++ in which every row and column are arrays of linked lists from a class I created (aptly named: LinkedList). I want to write a class that is a "smart" pointer to one cell in this matrix. In that class, let say LIPointer, I will implement a ++ operator function for moving in the linked lists of the matrix. Is there an elegant way of doing this without moving the references of the matrix arrays and sized elements each time I create a linkedlistPointer? I can't use stl::array etc. because I have to build them myself. Here are the declarations: class LinkedItem { private: int Column, Row; double Value; LinkedItem* Right; LinkedItem* Down; public: ... }; class SparseLinkedMatrix { private: //members int ColSize; int RowSize; LinkedItem ** Columns; LinkedItem ** Rows; public: //functions SparseLinkedMatrix(); ... }; class LIPointer; private: LinkedItem * CellPointer; public: LIPointer(); void operator++();//??? ... }; Any advice or direction would be appreciated. Update: It needs to run on the whole matrix. That is why I think I need to move (by reference) the arrays and the size of the matrix. The intended effect is that this would from the last cell in the linked list of the first row to the first cell in the second row.
For compressed row matrices, I use something like: std::vector<std::map<size_t, double> > matrix; I can then add an entry using: matrix[row][col] += val; For each row, I can then iterate through the column entries in ascending order and read out the value. Edit: The person posing the question does point out that they cannot use the STL. Perhaps they can use some kind of map versus a linked list. Otherwise I suggest using a vector of linked lists and keep adding entries to the end of each list. Then do a sort of each linked list when adding entries has been completed.
399,942
399,960
C++ variable with same name, context : global and private,
In the following code, g++ gives this error : 1.cpp: In member function void W::test()': 1.cpp:6: error:int F::glob' is private 1.cpp:19: error: within this context But, shouldn't the globally declared variable 'glob' be used here, instead of the "private" "glob"? #include <iostream.h> int glob; class F { int glob; public: void readIt() { cin >> glob; } }; class W : public F { public: void test() { glob--; } }; int main() { }
Variables and functions are accessed using scoping rules, not visbility rules. Because F::glob is the glob in the scope of W::test(), it is used. However, W::test() does not have access to F::glob, and an error results. The compiler does not check for ::glob because something else preceeds it in scope "priority" (not sure for the exact term).
399,946
400,769
How often do you check for an exception in a C++ new instruction?
I just started reading Effective C++ today and got to the point where the author talks about the operator new. The book explains very well how you can catch (with various degrees of elegance) the std::bad_alloc exception that the operator new can raise if you run out of memory. My question is: How often do you check for the case when there isn't enough memory to instantiate a object, if at all? and why? Is it worth the hassle?
I catch exceptions when I can answer this question: What will you do with the exception once you've caught it? Most of the time, my answer is, "I have no idea. Maybe my caller knows." So I don't catch the exception. Let it bubble up to someone who knows better. When you catch an exception and let your function proceed running, you've said to your program, "Never mind. Everything's fine here." When you say that, by golly, everything had better be fine. So, if you've run out of memory, then after you've handled std::bad_alloc, you should not be out of memory anymore. You shouldn't just return an error code from your function, because then the caller has to check explicitly for that error code, and you're still out of memory. Your handling of that exception should free some memory. Empty some caches, commit some things to disk, etc. But how many of the functions in your program do you really want to be responsible for reducing your program's memory usage? If you cannot solve the problem that triggered the exception, then do not handle the exception.
400,116
400,127
what is the purpose and return type of the __builtin_offsetof operator?
What is the purpose of __builtin_offsetof operator (or _FOFF operator in Symbian) in C++? In addition what does it return? Pointer? Number of bytes?
It's a builtin provided by the GCC compiler to implement the offsetof macro that is specified by the C and C++ Standard: GCC - offsetof It returns the offset in bytes that a member of a POD struct/union is at. Sample: struct abc1 { int a, b, c; }; union abc2 { int a, b, c; }; struct abc3 { abc3() { } int a, b, c; }; // non-POD union abc4 { abc4() { } int a, b, c; }; // non-POD assert(offsetof(abc1, a) == 0); // always, because there's no padding before a. assert(offsetof(abc1, b) == 4); // here, on my system assert(offsetof(abc2, a) == offsetof(abc2, b)); // (members overlap) assert(offsetof(abc3, c) == 8); // undefined behavior. GCC outputs warnings assert(offsetof(abc4, a) == 0); // undefined behavior. GCC outputs warnings @Jonathan provides a nice example of where you can use it. I remember having seen it used to implement intrusive lists (lists whose data items include next and prev pointers itself), but i can't remember where it was helpful in implementing it, sadly.
400,257
400,293
How can I pass a class member function as a callback?
I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors. Here is what I did from my constructor: m_cRedundencyManager->Init(this->RedundencyManagerCallBack); This doesn't compile - I get the following error: Error 8 error C3867: 'CLoggersInfra::RedundencyManagerCallBack': function call missing argument list; use '&CLoggersInfra::RedundencyManagerCallBack' to create a pointer to member I tried the suggestion to use &CLoggersInfra::RedundencyManagerCallBack - didn't work for me. Any suggestions/explanation for this?? I'm using VS2008. Thanks!!
That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument. Instead you can pass a static member function as follows, which are like normal non-member functions in this regard: m_cRedundencyManager->Init(&CLoggersInfra::Callback, this); The function can be defined as follows static void Callback(int other_arg, void * this_pointer) { CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer); self->RedundencyManagerCallBack(other_arg); }
400,903
401,514
Borland C++ Builder 5 - Cancel Via Escape Key Not Working
I'm having a rather perplexing problem with the Escape key handler on a dialog box in Borland C++ Builder 5. Are there any other requirements for the Escape key to fire a cancel event (other than those I've listed below)? The "Cancel" button (a TBitBtn) has its Cancel property set to true. The "Cancel" button has its Default property set to false. The "Cancel" button has its modalResult set to mrCancel. Note: I'm working with an old legacy app that is still being compiled in Borland C++ Builder 5. We have a separate project to replace it - I'm just doing end of life maintenance. Update Four months later I've finally stopped scratching my head...it turns out that the parent form for the application had a run-time OnShortCut handler defined. I just needed to disable that for the Esc handler to work on the child dialog.
You should check all possible ways the cancel event could be blocked: First of all, check if clicking the cancel button actually closes the form. Then check if any other button has its Cancel property set to true. After that check all key event handlers, don't forget the event handlers of the form, especially if you have KeyPreview enabled. If you still don't find the problem, check if another component has its ShortCut property set to handle the escape key. Also check if there are any keyboard hooks active.
401,621
401,801
Best way to for C++ types to self register in a list?
Suppose I have some per-class data: (AandB.h) class A { public: static Persister* getPersister(); } class B { public: static Persister* getPersister(); } ... and lots and lots more classes. And I want to do something like: persistenceSystem::registerPersistableType( A::getPersister() ); persistenceSystem::registerPersistableType( B::getPersister() ); ... persistenceSystem::registerPersistableType( Z::getPersister() ); ... for each class. My question is: is there a way to automate building a list of per-type data so that I don't have to enumerate each type in a big chunk (as in the above example)? For example, one way you might do this is: (AutoRegister.h) struct AutoRegisterBase { virtual ~AutoRegisterBase() {} virtual void registerPersist() = 0; static AutoRegisterBase*& getHead() { static AutoRegisterBase* head= NULL; return head; } AutoRegisterBase* next; }; template <typename T> struct AutoRegister : public AutoRegisterBase { AutoRegister() { next = getHead(); getHead() = this; } virtual void registerPersist() { persistenceSystem::registerPersistableType( T::getPersister() ); } }; and use this as follows: (AandB.cxx: ) static AutoRegister<A> auto_a; static AutoRegister<B> auto_b; Now, after my program starts, I can safely do: (main.cxx) int main( int, char ** ) { AutoRegisterBase* p = getHead(); while ( p ) { p->registerPersist(); p = p->next; } ... } to collect each piece of per-type data and register them all in a big list somewhere for devious later uses. The problem with this approach is that requires me to add an AutoRegister object somewhere per type. (i.e. its not very automatic and is easy to forget to do). And what about template classes? What I'd really like is for the instantiation of a template class to somehow cause that class to get automatically registered in the list. If I could do this I would avoid having to have the user of the class (rather than the author) to remember to create a: static AutoRegister< SomeClass<X1> > auto_X1; static AutoRegister< SomeClass<X2> > auto_X2; ... etc.... for each template class instantiation. For FIW, I suspect there's no solution to this.
You can execute something before main once if a instantiation of a template is made. The trick is to put a static data member into a class template, and reference that from outside. The side effect that static data member triggers can be used to call the register function: template<typename D> struct automatic_register { private: struct exec_register { exec_register() { persistenceSystem::registerPersistableType( D::getPersister() ); } }; // will force instantiation of definition of static member template<exec_register&> struct ref_it { }; static exec_register register_object; static ref_it<register_object> referrer; }; template<typename D> typename automatic_register<D>::exec_register automatic_register<D>::register_object; Derive the class you want to be auto-registered from automatic_register<YourClass> . The register function will be called before main, when the declaration of referrer is instantiated (which happens when that class is derived from, which will implicitly instantiate that class from the template). Having some test program (instead of the register function, a function do_it is called): struct foo : automatic_register<foo> { static void do_it() { std::cout << " doit "; } }; int main() { std::cout << " main "; } Yields this output (as expected): doit main
401,812
401,879
What is the proper way to cast from an 'OLE_HANDLE' to an 'HICON'?
What is the proper way to cast from an 'OLE_HANDLE' to an 'HICON' for an x64 target build? In particular with a normal C-Style cast, I get this warning when compiling with an x64 config: warning C4312: 'type cast' : conversion from 'OLE_HANDLE' to 'HICON' of greater size Here is the offending code: imgList.Add((HICON)ohIcon); The above code works fine for me, but I want to get rid of the warning when building for x64.
The H gives it away, in this case the library code has created a distinct type to give you a little more type safety (in the days of old C APIs). They are actually both HANDLEs, which is a kernel object that doesn't really care what the resource is, just that you have a 'handle' to it. Remember the API is a C one, so use C style casts, and when you come to delete it, use DeleteObject(). edit: 64 bits eh... the problem's because MS updated Handles to be 64 bits, but left the OLE stuff alone. Fortunately, all they did was pad the extra bits with zeros. Try using the LongToHandle conversion routines and see the MIDL porting guide - scroll about halfway down to the "USER and GDI handles are sign extended 32b values" section.
401,851
404,244
Naming convention for Qt widgets
I'm working with a group of other programmers on an open source project built using C++ and Qt. Now, we need a naming convention for widgets (and other variables generally) to use it as a standard in all of our code so that, the code gets better readability and we get better coordination between programmers. Any advice? EDIT: Am not talking about naming new classes, instead I am talking about naming instances of Qt Widgets, let's say I have a text edit for user name, should I name it txtEdtUsrNm? And in that case, how am I supposed to choose derivations?
As long as you are thinking along these lines, I'd start by reading this QtQuarterly article from start-to-finish. Designing Qt-Style C++ APIs That said, one thing that we do is to put the "use" of the instance as the first part and the last full word of the class as the last part. So, your "user name" QTextEdit is QTextEdit * userNameEdit = new QTextEdit(this); If there is ambiguity, such as QListView and QTreeView, pick the last unabiguous section. QListView * userListView; You can figure out abbreviations how you like (such as "Lbl" for QLabel), but generally, the whole word has worked and has been easy to read. On the other hand, we are not too strict about this and it might be more important to name the intention of the instance variable without the class name because if, in the future, you want to change the class, you get to change the name which, in the absence of good refactoring tools, is a pain. Maybe figure out the general widgets you use the most, and pick a naming convention for the most general super-classes and let everything else go. Example list of things that adhere to the convention: layout = All classes that end in "Layout" and inherit QLayout button = All classes that end in "Button" and inherit QAbstractButton The QAbstractClassName classes are a good place to think about what should be in that list.
402,314
403,511
How do you identify (and get access to) modules/debug symbols to use when provided a windows .dmp or .minidmp
In a way following on from reading a windows *.dmp file Having received a dump file from random customer, running the debug session to see the crash, you often find it is in a MS or other third party library. The next issue is that you may not have knowledge of the PC setup to such an extent that you can ensure you have the actually modules available. For instance I'm currently stuck trying to get symbols to load for ntdll.dll (5.01.2600.5512). In MSVC 2005 the path column in the modules list window shows a * before the fully pathed file name, and refuses to load symbols I have downloaded for XP/SP1/SP1a/SP2/SP3. I have the symbol server setup to download from the internet and store in a local cache which seems to have been working fine for modules that I do have on my PC. Using GUI equivelant to the method Set _NT_SYMBOL_PATH=srv*d:\SymbolCache*\\server1\Third-Party-PDB;srv*d:\SymbolCache*\\server2\Windows\Symbols*http://msdl.microsoft.com/download/symbols Perhaps I have the wrong symbols, but as new ones are not downloading where do I go to next? Do I have to contact the customer and ask what SP they have installed, and any other patches? Do I have to install that machine and then run up the debugger with the dmp file to get the symbols I need?
What are you using to debug the minidump? I.e., WinDBG or Visual Studio? And how was the minidump generated? There should be enough information in the minidump to resolve system dll symbols correctly. Are you using a local download of symbols or http://msdl.microsoft.com/? Update: You should be able to add the public microsoft symbol store to Tools->Options->Debugging->Symbols->Symbol file (.pdb) locations, and then manually load the symbols by right clicking on the module in the Modules window and loading them if it isn't done automatically. It's also possibly (likely) that VS 2005 doesn't look at _NT_SYMBOL_PATH to resolve minidump symbols.
402,316
402,320
Learning Algorithm and Saving Data in Software
I'm coming from a web-development background and I am wondering how I would make a learning algorithm in Java/C++. Not so much the algorithm part, but making the program "remember" what it learned from the previous day. I would think something like saving a file, but I suspect their might be an easier way. Apologies if this question is just over the top stupid. Thanks.
I think that would depend a bit on the problem domain. You might want to store learned "facts" or "relationships" in a DB so that they can be easily searched. If you are training a neural network, then you'd probably just dump the network state to a file. In general, I think once you have a mechanism that does the learning, the appropriate storage representation will be relatively apparent. Maybe if you can flesh out your plan on what kind of learning you'd like to implement, people can provide more guidance on what the implementation should look like, including the state storage.
402,432
402,456
C++ Returning and Inserting a 2D array object
I am trying to return an array Data Member from one smaller 2D Array Object, and trying to insert the array into a larger 2D array object. But when attempting this, I came into two problems. First problem is that I want to return the name of the 2D array, but I do not know how to properly syntax to return 2D Array name. This is what my 2D Array data member looks like private: int pieceArray[4][4]; // 2D Smaller Array and I want to return this array into a function, but this one causes a compiler error: int Piece::returnPiece() { return pieceArray; //not vaild // return the 2D array name } I tired using this return type and it worked: int Piece::returnPiece() { return pieceArray[4][4]; } But I am unsure if this is what I want, as I want to return the array and all of it's content. The other problem is the InsertArray() function, where I would put the returnPiece() function in the InsertArray()'s argument. The problem with the InsertArray() is the argument, heres the code for it: void Grid::InsertArray( int arr[4][4] ) //Compiler accepts, but does not work { for(int i = 0; i &lt x_ROWS ; ++i) { for (int j = 0; j &lt y_COLUMNS ; ++j) { squares[i][j] = arr[i][j]; } } } The problem with this is that it does not accept my returnPiece(), and if i remove the "[4][4]", my compiler does not accept. Mostly all these are syntax errors, but how do I solve these problems? Returning the whole pieceArray in returnPiece() The correct syntax for the argument in InsertArray() The argument of InsertArray() accepting the returnPiece() These 3 are the major problems that I need help with, and had the same problem when I attempt to use the pointer pointer method. Does anyone know how to solve these 3 problems?
When passing your array around, you have to decide whether or not you want to make a copy of the array, or if you just want to return a pointer to the array. For returning arrays, you can't (easily) return a copy - you can only return a pointer (or reference in C++). For example: // Piece::returnPiece is a function taking no arguments and returning a pointer to a // 4x4 array of integers int (*Piece::returnPiece(void))[4][4] { // return pointer to the array return &pieceArray; } To use it, call it like so: int (*arrayPtr)[4][4] = myPiece->returnPiece(); int cell = (*arrayPtr)[i][j]; // cell now stores the contents of the (i,j)th element Note the similarity between the type declaration and using it - the parentheses, dereferencing operator *, and brackets are in the same places. Your declaration for Grid::InsertArray is correct - it takes one argument, which is a 4x4 array of integers. This is call-by-value: whenever you call it, you make a copy of your 4x4 array, so any modification you make are not reflected in the array passed in. If you instead wanted to use call-by-reference, you could pass a pointer to an array instead: // InsertArray takes one argument which is a pointer to a 4x4 array of integers void Grid::InsertArray(int (*arr)[4][4]) { for(int i = 0; i < x_ROWS; i++) { for(int j = 0; j < y_COLUMNS ; j++) squares[i][j] = (*arr)[i][j]; } } These type declarations with pointers to multidimensional arrays can get really confusing fast. I recommend making a typedef for it like so: // Declare IntArray4x4Ptr to be a pointer to a 4x4 array of ints typedef int (*IntArray4x4Ptr)[4][4]; Then you can declare your functions much more readable: IntArray4x4Ptr Piece::returnPiece(void) { ... } void Grid::InsertArray(IntArray4x4Ptr arr) { ... } You can also use the cdecl program to help decipher complicated C/C++ types.
402,598
406,278
Debugging C++ lib with eclipse
I am working on project in Linux which involves 1) Static Lib in C++ 2) GUI developed in C++/QT which uses static lib. Now both the lib and gui are build from command prompt using makefiles. I am trying to debug both like when I hit one button, call should go from GUI to lib. Is it possible to do like this in Linux with eclipse? I can easily follow same debugging procedure in Windows using Visual studio and attaching lib to GUI but I cannot find any good way to do here with eclipse. I have tried many IDEs/debuggers like Anjuta Code Blocks. DDD,Kdbg but none is working properly. I am not sure that if I am wrong or is it much complex to debug? Can some one suggest one proper way to debug ?
Well I figured it out.. I am currently using Kdevelop.. With Kdevelp we can create QT project as well as c++(lib) project. And there is option to attach process also. So I can step through lib code by attaching GUI .
402,824
402,898
Automatic generation of function stubs
Is there any Visual Studio add-on (or windows/unix stand-alone program) that creates stub implementations in the cpp file for the functions (including class member functions) that are defined in the header file?
I have the same problem before and now I am using trial version of Visual Assist X. The task mentioned can be done by right clicking on the method name -> Refactor -> Create Implementation and then Refactor -> Move Implementation to CPP file. I am no Visual Assist X's affiliate or what, but this really increases my coding speed with Visual C++ dramatically.
402,969
403,024
What makes the Java compiler so fast?
I was wondering about what makes the primary Java compiler (javac by sun) so fast at compilation? ..as well as the C# .NET compiler from Microsoft. I am comparing them with C++ compilers (such as G++), so maybe my question should have been, what makes C++ compilers so slow :)
That question was nicely answered in this one: Why does C++ compilation take so long? (as jalf pointed out in the comments section) Basically it's the missing modules concept of C++, and the aggressive optimization done by the compiler.
402,992
403,140
Passing function Pointers in C++
i want to do this simple piece of code work. #include <iostream> #include <windows.h> void printSome (int i) { std::cout << i << std::endl; } void spawnThread (void (*threadName)(int i)) { CreateThread ( 0, // default security attributes 0, // use default stack size (LPTHREAD_START_ROUTINE)threadName, // thread function name (LPVOID)i, // argument to thread function 0, // use default creation flags 0 // returns the thread identifier ); } int main () { spawnThread(printSome(155)); } i am on windows, using vs. Any help will be greatly appriciated.
Personally, I wouldn't consider passing in a function pointer like you are trying to do as very C++ like. That's coding C in C++ Instead, I'd wrap that thing in a class. The big advantage there is you can just override the class to have however many members you want, rather than having to perform greazy casting tricks to get at your parameters every time. The code's a little long-winded, so I pushed it to the end. But what it lets you do is something like this: class print_some : public basic_thread { private: int i; public: print_some (int i) : i(i) {}; action_callback () { std::cout << i << std::endl; } } int main () { print_some printer (155); } Here's some exerpted example code from one of our classes that does this: class basic_thread : { public: basic_thread(); protected: unsigned long m_ThreadId; virtual void action_callback () {}; // Internal routine used to bridge between OS callback format and // action_callback. *Must* be static for the OS. static unsigned long __stdcall self_calling_callback (void *parameter); } ...and in the .cpp: unsigned long __stdcall basic_thread::self_calling_callback (void *parameter) { if (parameter) { basic_thread * thread = reinterpret_cast<basic_thread *>(parameter); thread->action_callback(); } return 0; // The value returned only matters if someone starts calling GetExitCodeThread // to retrieve it. } basic_thread::basic_thread () { // Start thread. m_Handle = CreateThread(NULL, 0, self_calling_callback, (PVOID)this, 0, &m_ThreadId ); if( !IsHandleValid() ) throw StartException("CreateThread() failed", GetLastError()); }
403,349
403,366
unicode char comparing to non unicode char, but no warning nor error
Why does the following code NOT give an error, nor any type of a warning about an implicit conversion? std::wstring str = L"hi"; if(str[0] == 'h') cout<<"strange"<<endl; The proper normal code is: std::wstring str = L"hi"; if(str[0] == L'h') cout<<"strange"<<endl; Compiler: visual studio 2005 Warning level: level 4 (highest)
It doesn't give a warning because the comparison is valid. In general, you can always compare integral types, they just get promoted to wider types as needed. And I'm pretty sure some compilers would issue a warning about this. Which one are you using? (In any case, warnings are compiler-specific, and they're not required to warn about this or anything else)
403,420
403,452
Convert XSD into SQL relational tables
Is there something available that could help me convert a XSD into SQL relational tables? The XSD is rather big (in my world anyway) and I could save time and boring typing if something pushed me ahead rather than starting from scratch. The XSD is here if you want to have a look. It's a standardized/localized format to exchange MSDS.
Altova's XML Spy has a feature that will generate SQL DDL Script from an XSD file. XML Spy will cost you some money though. Interestingly enough, a developer used a really clever trick of using an XSLT translation to create the DDL script from an XSD file. They have outlined it in two parts here and here. I might have to try this out myself for future use... EDIT: Just found this question asked previously here...
403,747
403,907
Bests practices for localized texts in C++ cross-platform applications?
In the current C++ standard (C++03), there are too few specifications about text localization and that makes the C++ developer's life harder than usual when working with localized texts (certainly the C++0x standard will help here later). Assuming the following scenario (which is from real PC-Mac game development cases): responsive (real time) application: the application has to minimize non-responsive times to "not noticeable", so speed of execution is important. localized texts: displayed texts are localized in more than two languages, potentially more - don't expect a fixed number of languages, should be easily extensible. language defined at runtime: the texts should not be compiled in the application (nor having one application per language), you get the chosen language information at application launch - which implies some kind of text loading. cross-platform: the application is be coded with cross-platform in mind (Windows - Linux/Ubuntu - Mac/OSX) so the localized text system have to be cross platform too. stand-alone application: the application provides all that is necessary to run it; it won't use any environment library or require the user to install anything other than the OS (like most games for example). What are the best practices to manage localized texts in C++ in this kind of application? I looked into this last year that and the only things I'm sure of are that you should use std::wstring or std::basic_string<ABigEnoughType> to manipulate the texts in the application. I stopped my research because I was working more on the "text display" problem (in the case of real-time 3D), but I guess there are some best practices to manage localized texts in raw C++ beyond just that and "use Unicode". So, all best-practices, suggestions and information (cross-platform makes it hard I think) are welcome!
At a small Video Game Company, Black Lantern Studios, I was the Lead developer for a game called Lionel Trains DS. We localized into English, Spanish, French, and German. We knew all the languages up front, so including them at compile time was the only option. (They are burned to a ROM, you see) I can give you information on some of the things we did. Our strings were loaded into an array at startup based on the language selection of the player. Each individual language went into a separate file with all the strings in the same order. String 1 was always the title of the game, string 2 always the first menu option, and so on. We keyed the arrays off of an enum, as integer indexing is very fast, and in games, speed is everything. ( The solution linked in one of the other answers uses string lookups, which I would tend to avoid.) When displaying the strings, we used a printf() type function to replace markers with values. "Train 3 is departing city 1." Now for some of the pitfalls. 1) Between languages, phrase order is completely different. "Train 3 is departing city 1." translated to German and back ends up being "From City 1, Train 3 is departing". If you are using something like printf() and your string is "Train %d is departing city %d." the German will end up saying "From City 3, Train 1 is departing." which is completely wrong. We solved this by forcing the translation to retain the same word order, but we ended up with some pretty broken German. Were I to do it again, I would write a function that takes the string and a zero-based array of the values to put in it. Then I would use markers like %0 and %1, basically embedding the array index into the string. Update: @Jonathan Leffler pointed out that a POSIX-compliant printf() supports using %2$s type markers where the 2$ portion instructs the printf() to fill that marker with the second additional parameter. That would be quite handy, so long as it is fast enough. A custom solution may still be faster, so you'll want to make sure and test both. 2) Languages vary greatly in length. What was 30 characters in English came out sometimes to as much as 110 characters in German. This meant it often would not fit the screens we were putting it on. This is probably less of a concern for PC/Mac games, but if you are doing any work where the text must fit in a defined box, you will want to consider this. To solve this issue, we stripped as many adjectives from our text as possible for other languages. This shortened the sentence, but preserved the meaning, if loosing a bit of the flavor. I later designed an application that we could use which would contain the font and the box size and allow the translators to make their own modifications to get the text fit into the box. Not sure if they ever implemented it. You might also consider having scrolling areas of text, if you have this problem. 3) As far as cross platform goes, we wrote pretty much pure C++ for our Localization system. We wrote custom encoded binary files to load, and a custom program to convert from a CSV of language text into a .h with the enum and file to language map, and a .lang for each language. The most platform specific thing we used was the fonts and the printf() function, but you will have something suitable for wherever you are developing, or could write your own if needed.
403,929
403,958
Which compiler is correct for the following overloading/specialization behavior?
Consider the following code: #include <stdio.h> namespace Foo { template <typename T> void foo(T *, int) { puts("T"); } template <typename T> struct foo_fun { static void fun() { foo((T *)0, 0); }; }; } namespace Foo { void foo(int *, int) { puts("int"); } } using namespace Foo; int main() { foo_fun<int> fun; fun.fun(); } What's the expected output? "T" or int? One compiler (gcc 4.0.1 from Apple's Xcode 3.1.2) output "int", two other compilers (gcc 4.1.2 and 4.1.3) output "T". If I move foo(int *, int) declaration/definition before the foo(T *, int) version, all output "int". Is the order of overloading/specialization in this case defined by the current standard?
The second void foo(... is an overload (and not a specialization) which is not visible at the definition of foo_fun::fun so it won't be found in the context of the template definition. Because T* is a dependent type, resolution of foo in the expression foo((T*)0, 0) will be delayed until template instantiation time and the context of the instantiation will also be considered. However, 14.6.4.2 of the standard says that if the function name is an unqualified-id but not a template-id then for non-ADL lookup only functions visible at the point of definition of the template are considered. There are no function arguments from the Foo namespace so no argument dependent lookup occurs, hence the template version of foo is called and not the non-template overload. Many thanks to litb for the corrections to this answer. If you made it a specialization as below, then as specializations are chosen at template instantiation time, the specialization can be called so long as the relevant specialization is visible at the point at which the function template is first instantiated for int. namespace Foo { template<> void foo<int>(int *, int) { puts("int"); } } Chapter 14 of the current standard, but it's not very readable :) Edit: If I had to pick the most relevant part of the standard it would probably be 14.6 [temp.res] para 9. (Slightly abbreviated) If a name does not depend on a template-parameter, a declaration for that name shall be in scope at the point at where the name appears in the template definition; the name is bound to the declaration found at that point and this binding is not affected by declarations that are visible at the point of instantiation. Edit, edit: But you also need to take into account 14.6.4.2 [temp.dep.candidate]. It is very difficult and dangerous to try and reference the standard because of all the interdependencies, this answer is a case in point.
403,946
403,954
Trying to get rid of a c++ boost warning
Whenever I include boost in my project I get a million of these warnings. Does anyone know how I can get rid of the warnings? ../depends\boost/config/abi_prefix.hpp(19) : warning C4103: 'depends\boost\config\abi_prefix.hpp' : alignment changed after including header, may be due to missing #pragma pack(pop) I know I can do a #pragma to disable the warning, but I'd like to know the reason for these warnings.
The reason is that boost doesn't push/pop these pragmas in every file that needs data to be packed. They #include a separate file which does the push (abi_prefix.hpp), and then another (abo_suffix.hp) afterwards which does the pop. That allows them to reuse the same #pragma pack code everywhere, which is handy as it may vary between compilers. It's perfectly safe though. The #pragma push is followed by a pop, it's just included from a different file. So you should probably just disable that error.
404,169
415,861
GNU Compiler Debug 'Level'
While browsing the various option switches for my compiler (GNU C++ 3.2.3 is supported by my organization for my given hardware configuration), I ran across this: -glevel : Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3. I compiled a test program with a few macros (such as a loop, a if-then-else on an argument), then tried the commercial debugger TotalView, and GDB on the code compiled -g3. I didn't see any difference (macros were not expanded to their original code, I couldn't 'step into' the macros, etc.). Anyone here had the experience of getting extra debugging 'features' using -g3 on GNU compilers?
Your question appears to imply that you don't understand what macros are. Of course you can't step into a macro. The -g3 is quite useful for "macro heavy" programs. Consider: int main() { int i; for (i = 0; i < 20; ++i) { #define A(x) case x: printf(#x "\n"); break switch(i) { A(1); A(2); A(3); A(4); /* line 7 */ #undef A #define A(x) case 10+x: printf("10+" #x "\n"); break A(1); A(2); /* line 10 */ } } return 0; } Without -g3, when you are stopped on line 7 or 10, you may have to search quite a lot for definition of A(), and there could be many such definitions, so you would then have to figure out which one is "current". With -g3, GDB can to do the heavy lifting for you: (gdb) b 7 Breakpoint 1 at 0x4004cc: file m.c, line 7. (gdb) b 10 Breakpoint 2 at 0x4004fc: file m.c, line 10. (gdb) r Breakpoint 1, main () at m.c:7 7 A(1); A(2); A(3); A(4); (gdb) info macro A Defined at /tmp/m.c:5 #define A(x) case x: printf(#x "\n"); break (gdb) c 1 2 3 4 Breakpoint 2, main () at m.c:10 10 A(1); A(2); (gdb) info macro A Defined at /tmp/m.c:9 #define A(x) case 10+x: printf("10+" #x "\n"); break (gdb) q
404,231
404,263
Using an enum as an array index
I have this enum: enum ButtonState { BUTTON_NORMAL = 0, BUTTON_PRESSED = 1, BUTTON_CLICKED = 2 }; const u8 NUM_BUTTON_STATES = 3; In my Button class I have member variables ButtonState state; and ButtonColors colors[NUM_BUTTON_STATES];. When drawing the button, I use colors[state] to get the colours for whatever state the button is in. My questions: Is this good programming style? Is there a better way to do it? (I usually only use enums with switch statements... using an enum as an array index doesn't feel right.) Do I have to specify the values of the enum? It seems to start from 0 by default and increment by 1 but is it guaranteed to work that way in all compilers?
Is this good programming style? I think so. I do the same thing quite frequently. Is there a better way to do it? class Button { public: // Used for array indexes! Don't change the numbers! enum State { NORMAL = 0, PRESSED, CLICKED, NUMBER_OF_BUTTON_STATES }; }; Drawback is that NUMBER_OF_BUTTON_STATES is now a valid Button::State value. Not a big issue if you are passing these values around as ints. But trouble if you are actually expecting a Button::State. Using an enum as an array index doesn't feel right. It's fine. Just DOCUMENT it, so the next guy knows what's going on! (That's what comments are for.) Do I have to specify the values of the enum? With no '=' assignment, enum's are supposed to start at zero and increment upwards. If a enum entry has an '=' assigned value, subsequent non '=' enum entries continue counting from there. Source: The Annotated C++ Reference Manual, pg 113 That said, I like to specify the initial value just to make the code that much clearer.
404,258
404,269
How do I erase a reverse_iterator from an stl data structure?
For some reason the following code fails. You can't simply erase a reverse_iterator by using its base() method. #include <set> #include <iostream> int main() { std::set<int> setOfInts; setOfInts.insert(1); setOfInts.insert(2); setOfInts.insert(3); std::set<int>::reverse_iterator rev_iter = setOfInts.rbegin(); std::set<int>::reverse_iterator nextRevIter = setOfInts.rbegin(); ++nextIter; while ( rev_iter != setOfInts.rend()) { // Find 3 and try to erase if (*rev_iter == 3) { // SEGFAULT HERE setOfInts.erase( rev_iter.base()); } rev_iter = nextRevIter; ++nextRevIter; } } How does one go about correctly doing the above? Given a reverse_iterator that corresponds to something you want to erase, how do you erase it? Note, erase won't take reverse_iterators unfortunately. It wants the real thing.
Apparently the solution is what base() returns is 1 off. The following identity holds for a reverse_iterator: &*(reverse_iterator(i)) == &*(i - 1) Or in other words, the reverse_iterator is always one pass the regular iterator it is the base of. Not sure why. In GCC Simply change // SEGFAULT HERE setOfInts.erase( rev_iter.base()); to // WORKS! setOfInts.erase( --rev_iter.base()); I'm definitely curious though as to why the identity above makes sense. In Visual Studio Coming back into work and trying this in visual studio, I see the above solution doesn't quite work. The "nextIter" becomes invalid on the erase. Instead, you need to save away the temporary from the erase to get the next iterator instead of keeping around a nextIter like above. set<int>::iterator tempIter = setOfInts.erase(--rev_iter.base()); rev_iter = setOfInts.erase(tempIter); So the final solution is int main() { using namespace std; set<int> setOfInts; setOfInts.insert(1); setOfInts.insert(2); setOfInts.insert(3); set<int>::reverse_iterator rev_iter = setOfInts.rbegin(); while ( rev_iter != setOfInts.rend()) { // Find 3 and try to erase if (*rev_iter == 3) { cout << "Erasing : " << *rev_iter; set<int>::iterator tempIter = setOfInts.erase( --rev_iter.base()); rev_iter = set<int>::reverse_iterator(tempIter); } else { ++rev_iter; } } } Note, associative containers do not return an iterator from erase. So this solution wouldn't work for map, multimap, etc.
404,311
404,317
Is there a way to set a pragma disable warning for visual studio for an entire solution?
Is there a way to set a pragma disable warning for visual studio for an entire solution?
Use the /w compiler switch for per-project suppression. I'm not aware of any way to do it solution wide without selecting all projects and adding it to the command-line for each project (which can be done in one operation).
404,468
404,480
typedef a std::string - Best practice
I am writing a library in standard C++ which does the phonetic conversion. I have used std::string as of now. But in future I may have to change this to someother (std::wstring or something else). So I need to write my library in such a way that I can switch this easily. I have done the following so far to achieve this. Created a header file which will be used by all CPP files Added a "typedef std::string" to this and used the new name everywhere in the file. If I need to change the type, I can simply change in the header file and it will be reflected everywhere. I'd appreciate if someone can see this is the correct approach or is there a better way to do this? Thanks
You can write template functions that will work with either type of string, or for that matter anything that has the proper methods. If you do the typedef as you suggest, you will need to change all your code in the future when you change the typedef. I'd recommend against it. Edit: the point is that string and wstring are not interchangeable. Sure, you'll be able to update your library by changing a single line, but that's just the start - changing the typedef means you're changing the public API of your library. You'll have to change and test all of the code that interacts with your library, and this might represent the majority of the work involved. It's even possible that a simple search and replace is sufficient to update your library, and then the typedef has bought you nothing. There's value in sticking to the standard types that everyone knows and understands.
404,513
404,517
Private member variables scope - C++
I am just starting with C++ and got some problems in understanding how the scope for private member variables in a class works. Please see the below code class Foo{ private: std::vector<int> container; public: // other methods }; int main(int argc, char* argv[]) { Foo* foo = new Foo; // other method calls to which foo is passed delete foo; return 0; } In the above code, variable "container" is a private member variable. I am invoking "Foo" instance and passing it to several other methods and classes. Following are my doubts What will be the scope of variable "container"? Will that variable exist until I delete the instance foo? Do I need to make the "container" as a pointer to vector? Thanks for the help
Yes, the lifetime of the container member will last as long as the object that contains it exists, which is until you call delete on the pointer pointing to it (foo in your case). No, there is no reason to do that. Making it a pointer requires you to create a dynamic object of vector<int> which you would need to manage the lifetime of (including calling delete on the container pointer). That's unnecessary here. Assuming you want the container last as long as the Foo object, you are fine with having it directly contained, without doing it with a pointer. Passing the foo pointer will just pass the pointer. The object that it points to will not be copied, only the pointer pointing to it if necassary. If you know Java, then it helps you if i tell you passing the pointer is the same as just passing a reference to an object in Java, say: Foo f = new Foo(); // just passes the reference (pointer in C++) to doIt. // the actual object is not copied doIt(f);
404,886
404,916
Alternative to CString::Format?
Is there any better alternative for doing string formatting in VC6, with syntax checking before substitution?
CString offers the Format method for printf-style formatting, but this isn't type-safe. For type-safe string formatting you could either use std::stringstream / std::wstringstream or the Boost Format library, although these both work with the C++ std::basic_string class template, and not the MFC CString class. I've used both of these successfully in VC6. Boost Format is nice because it allows you to use printf-like syntax, and will throw an exception if the arguments you supply don't match the format string, whereas string formatting with C++ iostreams tends to make your code quite verbose. Note that you can create a CString object from a std::string as follows: std::string s; CString str( s.c_str() ); I hope this helps!
404,934
404,939
Can someone explain this C++ notation?
if (vector1.x > ((float*)&vector1)[j]) Is j simply just an index into the vector? e.g. is C++ able to retrieve these values using array notation even though vector isn't an array? If so I'm guessing it achieves this by referencing vector by its address?
The C++ Standard says that casting a (pods) struct's pointer to a pointer of the type of its first element will yield a pointer to its first element: struct a { float a1; float a2; float a3; }; a o1; ((float*)&o1); // points to o1.a1 I suspect that code told the compiler not to add any padding between a1, a2 and a3, so that if it indexes the pointer, it will pointer exactly to the float it wants. So above ((float*)&o1)[1] // *would* return o1.a2 That's platform dependent, as padding can't be changed in Standard C++. Lookup how that code arranges it, and whether i'm right at all :)
405,039
405,068
"Permanent" std::setw
Is there any way how to set std::setw manipulator (or its function width) permanently? Look at this: #include <iostream> #include <iomanip> #include <algorithm> #include <iterator> int main( void ) { int array[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256 }; std::cout.fill( '0' ); std::cout.flags( std::ios::hex ); std::cout.width( 3 ); std::copy( &array[0], &array[9], std::ostream_iterator<int>( std::cout, " " ) ); std::cout << std::endl; for( int i = 0; i < 9; i++ ) { std::cout.width( 3 ); std::cout << array[i] << " "; } std::cout << std::endl; } After run, I see: 001 2 4 8 10 20 40 80 100 001 002 004 008 010 020 040 080 100 I.e. every manipulator holds its place except the setw/width which must be set for every entry. Is there any elegant way how to use std::copy (or something else) along with setw? And by elegant I certainly don't mean creating own functor or function for writing stuff into std::cout.
Well, it's not possible. No way to make it call .width each time again. But you can use boost, of course: #include <boost/function_output_iterator.hpp> #include <boost/lambda/lambda.hpp> #include <algorithm> #include <iostream> #include <iomanip> int main() { using namespace boost::lambda; int a[] = { 1, 2, 3, 4 }; std::copy(a, a + 4, boost::make_function_output_iterator( var(std::cout) << std::setw(3) << _1) ); } It does create its own functor, but it happens behind the scene :)