question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,556,168
1,556,219
Making a non-object resource RAII-compliant
in my code I use HANDLEs from windows.h. They are used like HANDLE h; if (!openHandleToSomething(arg1, arg2, &h)) { throw std::exception("openHandleToSomething error"); } /* Use the handle in other functions which can throw as well */ if (!CloseHandle(h)) { throw std::exception("closeHandle error"); } As you see, you have to insert this CloseHandle to every exception which can happen in the middle of acquiration and release. Therefore, it's likely you forget one (or there is a fancy SEH exception which you didn't know about) and voilà, you have your memory leak. Recently, I've read about RAII which should remove the headaches from such cases and should call this CloseHandle automatically. I've also seen that there is something like std::auto_ptr<someType> in C++ which solves the problem for resources which were allocated with new. However, since I don't use new and since HANDLE is just typedefed to be a void *, I wonder how I should use the std::auto_ptr<someType>. Somehow, it should be possible to give it a custom deleter function (if (!CloseHandle(h)) { throw std::exception("closeHandle error"); }). Creating a class would be another method since the destructor gets called any time an instance of it gets out of scope. However, it's just overkill to have a class for every simple thing. How can I fix these accidential memory leaks? Note that I would prefer solutions which are in pure C++ with no libraries and big dependencies except if they are really small and used in most of the environments anyways.
One idea that comes to mind is to use boost::shared_ptr with a custom deleter.
1,556,229
1,556,677
vector <unsigned char> vs string for binary data
Which is a better c++ container for holding and accessing binary data? std::vector<unsigned char> or std::string Is one more efficient than the other? Is one a more 'correct' usage?
You should prefer std::vector over std::string. In common cases both solutions can be almost equivalent, but std::strings are designed specifically for strings and string manipulation and that is not your intended use.
1,556,284
1,556,312
Is there a way to get the byte size of vectors through type alone?
How can I predict the size of a vector? #include <vector> #include <iostream> using namespace std; int main() { cout << sizeof(vector<char[8]>) << endl; cout << sizeof(vector<char[16]>) << endl; return 0; } [starlon@localhost LCDControl]$ ./test 12 12
Since vector<> itself is a class that does its own dynamic memory management, using the sizeof operator to ask it about size is not terribly meaningful. I suspect you will find that the value you calculate above will always be 12. You can ask a vector how many elements it contains using the .size() method. Also, the .capacity() method will tell you how many elements it has actually allocated memory for (even if they're not all in use yet). Remember that sizeof is evaluated at compile time, so it cannot know how many elements are inserted into the container later, at run time.
1,556,333
1,556,414
A question about C++ template syntax (STL library source code)
I am reading STL source code right now. Though I understand the meat in what I am reading in stl_list.h, I want to fully understand the following snippet (mainly related to the template syntax, I think). template class _List_base { ... typedef typename _Alloc::template rebind<_List_node<_Tp> >::other _Node_Alloc_type; //(1). ... typedef _Alloc allocator_type; get_allocator() const { return allocator_type(*static_cast< const _Node_Alloc_type*>(&this->_M_impl)); } // (2) ... }; Can someone explain why we need a "template" following _Alloc in line (1)? (and giving a full explanation of this line?) Can someone explain why we can cast _Node_Alloc_type to _Alloc in line (2)?
The template keyword is needed to identify the name rebind as a class template. Without it, rebind could be considered a variable or a constant (in this case a type due to the typename keyword) and the following < could be interpreted as a less-than operator. This is somewhat similar to the typename keyword (which is of course necessary to identify other as a type). Every allocator is required to provide a meta-function (i.e. a class template) called rebind that returns the same allocator but for a different type. In other words, Alloc<T>::rebind<U>::other names the same type as Alloc<U> The second part of your question is difficult to answer without more context. What is the type of _M_impl? How is that type defined?
1,556,581
1,556,685
Is it possible to create a linked list on the stack in C++?
I just started learning C++ couple of weeks ago. So now I have this school assignment problem that asks me to implement a linked-list without using "new" or anything to do with dynamically allocating memory (and cannot use any ADT from STL). The prof says that everything can be done on the stack, but how? I have been working on this since Friday and still stuck on this with absolutely no luck. It says: Keep a stack of the file names being read. Use the following data structure for the stack: struct Node { string fileName; Node *link; }; I tried to avoid using new but it always give me "segmentation fault" or "BUS error" when I pass the head of the list into a recursive method call. Any ideas about how I can work around this??
The difference between heap and stack are mainly (not only, but for the sake of this question mainly) where the memory is allocated and how it is freed. When you want to allocate a node on the heap, you say new Node and the system will provide you with the memory, keeps track of which chunks are used and which ones are free, and provides you with the means to free a chunk once you don't need it any longer. But you can just as well have a pool of nodes in an array on the stack. (Automatic variables are stack variables.) You can "allocate" from that pool, keep track of which nodes in the array are used and which are free, and mark unused ones as free ones you don't need them any longer. However, since the array's size is fixed at compile-time, this means that you have a maximum length for your list.
1,557,158
1,557,238
Converting an application to use dlls. class 'std::map<_Kty,_Ty>' needs to have dll-interface to be used by clients of class
This seems to be a common error, but most people online choose to just ignore the warning and move on. I do not wish to ignore the warning. Basically, when using __declspec(dllexport) to convert a project to use dlls, the compiler has trouble dealing with templates and stl objects. An explanation of the problem, and suggested solution are listed here. I have implemented the giant #define statement suggested for maps, to no avail. How do you make this work!? My code is absolutely littered with things like wchar_ts and std::maps, so hopefully a solution that doesn't involve writing something remotely complex for each class!
Read this similar thread for a good discussion of the topic. I would suggest either of the following: Use a static library Hide all template-related types and interfaces behind non-template compiler firewall or pimpl. After fighting with the linker changes from Visual C++ 6.0, to 2003, and then to 2005, I will never __declspec(dllexport) anything that has a template, bool, wchar_t, or time_t in the signature again. Actually, we just out-right stopped using DLLs altogether. Life is so much simpler now ;)
1,557,244
1,557,294
Abusing the comma operator
I'm looking for an easy way to build an array of strings at compile time. For a test, I put together a class named Strings that has the following members: Strings(); Strings(const Strings& that); Strings(const char* s1); Strings& operator=(const char* s1); Strings& operator,(const char* s2); Using this, I can successfully compile code like this: Strings s; s="Hello","World!"; The s="Hello" part invokes the operator= which returns a Strings& and then the operator, get called for "World!". What I can't get to work (in MSVC, haven't tried any other compilers yet) is Strings s="Hello","World!"; I'd assume here that Strings s="Hello" would call the copy constructor and then everything would behave the same as the first example. But I get the error: error C2059: syntax error : 'string' However, this works fine: Strings s="Hello"; So I know that the copy constructor does at least work for one string. Any ideas? I'd really like to have the second method work just to make the code a little cleaner.
I think that the comma in your second example is not the comma operator but rather the grammar element for multiple variable declarations. e.g., the same way that you can write: int a=3, b=4 It seems to me that you are essentially writing: Strings s="Hello", stringliteral So the compiler expects the item after the comma to be the name of a variable, and instead it sees a string literal and announces an error. In other words, the constructor is applied to "Hello", but the comma afterwards is not the comma operator of Strings. By the way, the constructor is not really a copy constructor. It creates a Strings object from a literal string parameter... The term copy constructor is typically applied to the same type.
1,557,245
1,557,266
Access Control for objects
Is it Possible to limit the functionality of class to certain objects only (in C++). What that would mean is, suppose there are 10 methods in a class and this class has 10 objects. Is it possible to have object1 & object2 access only 3 functions. Object3, object4,object5, object6 access 6 functions. and rest of the objects access all functions? I am trying to implement an access control system, where general users can see only some limited functionality. Previlaged users can have little bit more access and administrators have access to all functions. One approach is to use inheritance, something like this: class PublicFeatures { public: // add some methods here; }; class ProtectedFeatures:public PublicFeatures { public: // add some more methods here; }; class AdminFeatures:public ProtectedFeatures { public: // add rest of the methods here; }; In this case, we instantiate objects of any of three classes depending on the kind of access level we want. But what i am thinking is having just one class, and somehow restrict the access to some methods for that particular object. Is it possible to do such a thing? or i have to follow a different approach for implementing access control?
As far as I know, no. This is part, however, of Aspect Oriented Programming research. I saw something like what you need in this book: Aspect Oriented Software Development. The main issue you face is the lack of knowledge of "who is the caller" of your function. You could get along by requiring each caller to call your object's methods passing this as a form of authentication about itself. Far from perfect, but with this solution you can wrap each method in a pre-method doing the ACL. Another alternative would be to declare your implementation class totally private in terms of methods, and define a "bodyguard" class, declared friend of the first. The bodyguard class performs the calls on behalf of the caller (which is the only one authorized to do, due to the friend declaration). You still have the problem of authentication, and you are basically wrapping the whole target class behind its bodyguard object.
1,557,265
1,557,282
Unable to write file in C++
I'm trying to to the most basic of things .... write a file in C++, but the file is not being written. I don't get any errors either. Maybe I'm missing something obvious ... or what? I thought there was something wrong with my code, but I also tried a sample I found on the net and still no file is created. This is the code: ofstream myfile; myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt"); myfile << "Writing this to a file.\n"; myfile.close(); I've also tried creating the file manually beforehand, but it's not updated at all. I'm running Windows 7 64bit if that has got something to do with this. It's like file-write operations are completely forbidden and no error messages or exceptions are shown.
You need to open the file in write mode: myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt", ios::out); Make sure to look at the other options for that second argument, as well. If you're writing binary data you'll need ios::binary for example. You should also be checking the stream after opening it: myfile.open(... if (myfile.is_open()) ... Update: AraK is right, I forgot that an ofstream is in write mode by default, so that's not the problem. Perhaps you simply don't have write/create permissions to the directory? Win7 defaults a lot of directories with special permissions of "deny all". Or perhaps that file already exists and is read-only?
1,557,352
1,557,472
How do I escape the const_iterator trap when passing a const container reference as a parameter
I generally prefer constness, but recently came across a conundrum with const iterators that shakes my const attitude annoys me about them: MyList::const_iterator find( const MyList & list, int identifier ) { // do some stuff to find identifier return retConstItor; // has to be const_iterator because list is const } The idea that I'm trying to express here, of course, is that the passed in list cannot/willnot be changed, but once I make the list reference const I then have to use 'const_iterator's which then prevent me from doing anything with modifing the result (which makes sense). Is the solution, then, to give up on making the passed in container reference const, or am I missing another possibility? This has always been my secret reservation about const: That even if you use it correctly, it can create issues that it shouldn't where there is no good/clean solution, though I recognize that this is more specifically an issue between const and the iterator concept. Edit: I am very aware of why you cannot and should not return a non-const iterator for a const container. My issue is that while I want a compile-time check for my container which is passed in by reference, I still want to find a way to pass back the position of something, and use it to modify the non-const version of the list. As mentioned in one of the answers it's possible to extract this concept of position via "advance", but messy/inefficient.
If I understand what you're saying correctly, you're trying to use const to indicate to the caller that your function will not modify the collection, but you want the caller (who may have a non-const reference to the collection) to be able to modify the collection using the iterator you return. If so, I don't think there's a clean solution for that, unless the container provides a mechanism for turning a const interator into a non-const one (I'm unaware of a container that does this). Your best bet is probably to have your function take a non-const reference. You may also be able to have 2 overloads of your function, one const and one non-const, so that in the case of a caller who has only a const reference, they will still be able to use your function.
1,557,570
1,557,636
How can I sort a list when the sorting criterion requires an extra variable? C++
this is for an assignment so I will be deliberately general. My question is related to implementation decisions I already made--maybe they weren't good ones. I have a list of pointers to structs, e.g. list<MyStruct*> bob; At one point I've needed to sort these pointers by one of the data members of their targets and I was able to do that easily with bool sortbyarrival(const MyStruct* a, const MyStruct* b) { return a->arrival < b->arrival; } And then calling bob.sort(sortbyarrival); Works great. Now somewhere else I need to sort by a different criterion, which involves a counter in the program. I need something like return counter*a->arrival < counter*b->arrival; But the way I just described is the only way I know how to do a sort, I think, and I don't know how to pass my counter as an additional argument. How can I sort this list of pointers? ETA: The counter is just a variable in main. So ideally I could call something like bob.sort(sortbyratio, counter); or sort(bob.begin(), bob.end(), sortbyratio, counter);
Similar to ltcmelo's example, but if the objects themselves don't contain the counter: struct sort_with_counter { sort_with_counter(const double d): counter(d) {} bool operator()(const MyStruct* a, const MyStruct* b) { return(counter*a->arrival < counter*b->arrival); } const double counter; }; mylist.sort(sort_with_counter(5.0)); If your counter is an external variable like that though it won't affect the ordering (at least if it's positive - thanks onebyone!) - so this may in fact not be necessary at all (or maybe I misunderstand what you're after?). It's a useful technique in other cases though.
1,557,579
1,557,596
moc in QT wont compile my c++ header file. says its too different
ok wtf this is what moc tells me when i try to moc one of my header files. im doing this through Qt 4.5.3 command prompt and it says this: C:\Documents and Settings\The Fuzz\Desktop\GUI2>moc App_interface.h /**************************************************************************** ** Meta object code from reading C++ file 'App_interface.h' ** ** Created: Mon Oct 12 16:58:11 2009 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "App_interface.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'App_interface.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_App_interface[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0 // eod }; static const char qt_meta_stringdata_App_interface[] = { "App_interface\0" }; const QMetaObject App_interface::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_App_interface, qt_meta_data_App_interface, 0 } }; const QMetaObject *App_interface::metaObject() const { return &staticMetaObject; } void *App_interface::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_App_interface)) return static_cast<void*>(const_cast< App_interface*>(this)); return QWidget::qt_metacast(_clname); } int App_interface::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE C:\Documents and Settings\The Fuzz\Desktop\GUI2> any ideas??? im trying to use the Q_OBJECT Macro.
moc converts its input header into a generated file, which is printed on its output. You should send its output to a file, with a command like: moc App_interface.h > App_interface.h_moc then include that. If you're using QMake, I believe this process is automated.
1,557,714
1,565,249
How to automate Qt moc?
I have to run the following commands from Qt command prompt: qmake -project then make and this gives me the debug folder with the Moc file. This is strangely the only way my PC will generate the moc_.cpp file. So how can I automate the task of these commands so I don't have to use these commands again?
You should not run qmake -project multiple times. The -project option is meant to provide you a template project file for you to edit. An equivalent of what you are doing in an IDE would be creating a "New Project" every time you want to build. After you have the initial project, you should edit it manually, add files when you have new files, etc. If some header file changes, the generated Makefile will notice it and call moc on it to update the moc_*.cpp file automatically. So: Run qmake -project when you start working on a project. Run qmake when you want to generate Makefiles. Run make when you want to build the project.
1,558,013
1,558,027
Delete NULL but no compile error
I'm confused why the following C++ code can compile. Why does a call to delete the method of 0 not produce any error?! int *arr = NULL; // or if I use 0, it's the same thing delete arr; I did try to run it, and it did not give me any error at all...
The C++ language guarantees that delete p will do nothing if p is equal to NULL. For more info, check out Section 16.8,9 here:
1,558,052
1,558,105
Is it possible to translate twice in one OpenGL Matrix?
This is a homework question I am sorry but I am lost. What happens is the following I am asked to do a tiling of hexagons. Like the grid map in many Risk games and Wild Arms XF. I understand the current transformation is the matrix that translates the points I give to OpenGL to screen coordinates and if you apply a transformation it moves the the center point usually (0,0) to wherever. If you use glPushMatrix and glPopMatrix. What it does is make a replica of the current CT matrix and you do operations on it and when you pop it you return to the matrix without the transformation. The problem is the following I am trying to draw a hexagon, Translate(Displace, I like it better), draw another Hexagon, translate and Draw the last hexagon. What happens is the third hexagon dissapears from the face of the viewport and I am only raising it twice. What is funny is that consecutive rotates and scales give me no problems. so a small sample of the code. #include <windows.h> #include <stdio.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <iostream> #include <ctime> using namespace std; void initCT(void) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void drawHexagon() { glBegin(GL_LINE_STRIP); glVertex2i(0,0); glVertex2i(20, 0); glVertex2i(25,10); glVertex2i(20,20); glVertex2i(0,20); glVertex2i(-5,10); glVertex2i(0,0); glEnd(); } void myInit(void) { initCT(); glClearColor(1.0f,1.0f,1.0f,0.0f); glColor3f(0.0f, 0.0f, 0.0f); //set the drawin color glPointSize(1.0); //a 'dot'is 4 by 4 pixel glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluOrtho2D(-100.0, 400.0, -400.0, 400.0); glViewport(0, 0, 640, 480); } void myDisplay (void) { glClear (GL_COLOR_BUFFER_BIT); glMatrixMode( GL_MODELVIEW ); drawHexagon(); glTranslated(0.0f,20.0f,1.0f); drawHexagon(); glTranslated(0.0f,20.0f,1.0f); drawHexagon(); glTranslated(0.0f,20.0f,1.0f); drawHexagon(); glFlush(); //send all output to display } void main (int argc, char **argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (640, 480); glutInitWindowPosition (100, 150); glutCreateWindow ("Hexagon Tiling"); glutDisplayFunc (myDisplay); myInit(); glutMainLoop(); } I have used this code with the similar result, only two hexagons draw the others go into the Hitchhikers guide to the galaxy. I changed the colors of each hexagon and only the first two appear. THANK YOU GUYS YOU ARE THE MEN. I am sorry if giving the answer to one upsets the other but you both are right. Also for people using Google this is from Computer Graphics using Open GL there is an error in the translation function that the author gives you in the translate it should be 0 in the Z axis.
You're translating behind the camera; Each translation goes up in the y axis by 20, and in the z axis by 1. After the second step, your hexagons are behind the camera, and can't be seen in the viewport. Try glTranslated(0.0f,20.0f,0.0f); for each translation; that should help.
1,558,194
1,558,218
Learning and cross-platform development (C++)
I am writing a small C++ program for fun and for extending my C++ skill. Since its scope is relatively small, I also planning to try out cross-platform development by making this program support both Windows and Linux. I reckon my C++ proficiency is sitting somewhere between casual and intermediate level: OO, a bit of templates and design patterns, used STL before and trying to look into it more in details, ... However, while coding this little program, I find that the deeper I dig into C++, the more pain I feel, especially when I come to understanding and dealing with differences between different platform's/vendor's implementation. The use of cross-platform frameworks like Qt, ACE, Boost seems help to speed up development a lot thus make life easier, but I worry if this will beat my purpose. Can somebody give some advice if there is any "best practice" for doing C++ cross-platform development? Thanks.
Can somebody give some advice if there is any "best practice" for doing C++ cross-platform development? There are three things: Write your own code so that it's portable Wrap platform-specific APIs behind an abstraction/insulation/utility layer Choose cross-platform libraries You can choose option #2 and/or #3. Advantages of #3 over #2 tend to be things like, "It's already written, debugged, and supported"; and the disadvantages are like, "I have to learn it, I might have to pay for it, I can't necessarily support it myself, and it may not do exactly what I want." Developers will often prefer option #3 instead of #2, especially if it's free open source (which all three of the libraries that you cited are).
1,558,379
1,558,391
Why is nl_langinfo(CODESET) different from locale charmap?
This post originated from How do you get what kind of encoding your system uses in c/c++? I tried using nl_langinfo(CODESET) but I got ANSI_X3.4-1968 instead of UTF-8 (which is what I get when typing: locale charmap). Am I using nl_langinfo() wrong? How should I use it?
You need to first call setlocale(LC_ALL, ""); nl_langinfo always gives information about the current locale.
1,558,768
1,558,948
How do I open links from a TCppWebBrowser component in the systems default browser
We are using a TCppWebBrowser Component in our program as a kind of chatwindow, but since the TCppwebrowser is using the IExplorerengine all links that are clicked is opening in IExplorer. One idea I have is to cancel the navigation in Onbeforenavigate2 an do a Shell.execute, but where hoping for a more elegant solution like a windowsmessage i could handle or an event or something.
Assuming that TCppWebBrowser is like TWebBrowser in Delphi, something like the code below should get you going. The OnBeforeNavigate2 event gets fired before the TWebBrowser navigates to a new URL. What you do is cancel that navigation, and redirect the URL with ShellExecute to an external application (which is the default web browser as configured in Windows). In order to get the code below working, double click on your form, then enter the FormCreate event method content. Then drop a TWebBrowser, go do the events page of the object inspector and double click on the OnBeforeNavigate2 event and enter that code. Have fun with it! --jeroen unit MainFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, SHDocVw; type TForm1 = class(TForm) WebBrowser1: TWebBrowser; procedure FormCreate(Sender: TObject); procedure WebBrowser1BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OLEVariant; var Cancel: WordBool); private RedirectUrls: Boolean; end; var Form1: TForm1; implementation uses ShellAPI; {$R *.dfm} procedure TForm1.Create(Sender: TObject); begin WebBrowser1.Navigate('http://www.stackoverflow.com'); RedirectUrls := True; end; procedure TForm1.WebBrowser1BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OLEVariant; var Cancel: WordBool); var UrlString: string; begin if not RedirectUrls then Exit; UrlString := URL; ShellExecute(Self.WindowHandle, 'open', PChar(UrlString), nil, nil, SW_SHOWNORMAL); Cancel := True; end; end.
1,558,860
1,558,898
CListCtrl get item index
How do I get an item's index number using the caption text? I'm using CListCtrl class of MFC. I have the item's caption text, can I get the index for that item and then update its text. It will be helpful if you could provide an example.
CListCtrl::FindItem (MSDN link with example)
1,558,879
1,559,281
Regular expressions question
I've got the following string : const std::string args = "cmdLine=\"-d ..\\data\\configFile.cfg\" rootDir=\"C:\\abc\\def\""; // please note the space after -d I'd like to split it into 2 substrings : std::str1 = "cmdLine=..."; and std::str2 = "rootDir=..."; using boost/algorithm/string.hpp . I figured, regular expressions would be best for this but unfortunately I have no idea how to construct one therefore I needed to ask the question. Anyone capable of helping me out with this one?
To solve problem from your question the easiest way is to use strstr to find substring in string, and string::substr to copy substring. But if you really want to use Boost and regular expressions you could make it as in the following sample: #include <boost/regex.hpp> ... const std::string args = "cmdLine=\"-d ..\\data\\configFile.cfg\" rootDir=\"C:\\abc\\def\""; boost::regex exrp( "(cmdLine=.*) (rootDir=.*)" ); boost::match_results<string::const_iterator> what; if( regex_search( args, what, exrp ) ) { string str1( what[1].first, what[1].second ); // cmdLine="-d ..\data\configFile.cfg" string str2( what[2].first, what[2].second ); // rootDir="C:\abc\def" }
1,559,006
1,559,025
Wrapping C in C++, just for try/catch
So, I have a big piece of legacy software, coded in C. It's for an embedded system, so if something goes wrong, like divide by zero, null pointer dereference, etc, there's not much to do except reboot. I was wondering if I could implement just main() as c++ and wrap it's contents in try/catch. That way, depending on the type of exception thrown, I could log some debug info just before reboot. Hmm, since there are multiple processes I might have to wrap each one, not just main(), but I hope that you see what I mean... Is it worthwhile to leave the existing C code (several 100 Klocs) untouched, except for wrapping it with try/catch?
Division by zero or null pointer dereferencing don't produce exceptions (using the C++ terminology). C doesn't even have a concept of exceptions. If you are on an UNIX-like system, you might want to install signal handlers (SIGFPE, SIGSEGV, etc.).
1,559,334
1,560,389
Assignment across data types in C++
Possible Duplicate: Make VS compiler catch signed/unsigned assignments? I've compiled the following snippet of code in VC++ 2005/2008: unsigned long ul = ...; signed long l = ...; l = ul; and was expecting to see a compiler warning (Warning Level set to 4), but none was generated. Am I missing something obvious here? Thanks
I think it's a duplicate (here). Quoting the accepted answer: You need to enable warning 4365 to catch the assignment. That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does. (quamrana) You could also use #pragma warning(default: 4365) to enable. (ChrisN)
1,559,490
1,559,719
SidBySide: 3rd Party Dll refers to two versions of MSVCR80.DLL
We include a 3rd Party lib+DLL that recently causes a lot of trouble on installations. Using dependencywalker, we found that the dll itself refers to two different Versions of MSVCR80.DLL: Version 8.0.50727.4053 and Version 8.0.50727.42 alt text http://img101.imageshack.us/img101/1734/dependencywalk2.jpg In MOST cases installation makes no problems, even if we distribute none of both versions. But in a number of cases our installation just does not start. We then find messages in the windows system event log from the SideBySide manger: "Version of DLL does not match". In most cases again this problem can be resolved, by installing the .NET framework (although we do not use this). But now we have a case where this does not help. I know that a solution would be, to install both versions as a shared assembly, but that seems not to be easy, and besides that i would prefer a much simpler solution. Does anybody know a workaround? Can i somehow use only one version of the Dll? EDIT: I now tried cristians advice: D:\Develop\LEADTOOLS15\patch_maifest>mt.exe -inputresource:ltkrn15u.dll;#1 -out:old.manifest Microsoft (R) Manifest Tool version 5.2.3790.2075 Copyright (c) Microsoft Corporation 2005. All rights reserved. mt.exe : general error c101008c: Failed to read the manifest from the resource of file "ltkrn15u.dll". Ressource not found. If i view the dlls dependencies with full paths, i see the following: alt text http://img340.imageshack.us/img340/4122/dependencywalk3.jpg The lower MSVCR80.DLL is the one withe Version ...42. I dont understand this. Why does MSVCP80.DLL refer to a different Version of MSVCR80.DLL than the one besides it. Is that maybe a problem of the dependencywalker ?
Your best option is to ship the needed DLLs within your applications installer package. Use at least the version that your 3rd party DLL depends on. Microsoft offers standalone installers for its runtime DLLs (vcredits_*). The latest version for VisualStudio 2005 can be downloaded here. That is also the version that your DLL is linked against. You can silently launch the redistributable package from your installer. As a manual workaround for already installed systems, simply apply the redist installer on the target machine. If you choose this method, you don't need to be afraid of version conflicts, as applications depending on an older versions will be redirected to always use the most recent one. For a better understanding you have look at this MSDN articles.
1,559,695
1,559,956
Implementing the derivative in C/C++
How is the derivative of a f(x) typically calculated programmatically to ensure maximum accuracy? I am implementing the Newton-Raphson method, and it requires taking of the derivative of a function.
I agree with @erikkallen that (f(x + h) - f(x - h)) / 2 * h is the usual approach for numerically approximating derivatives. However, getting the right step size h is a little subtle. The approximation error in (f(x + h) - f(x - h)) / 2 * h decreases as h gets smaller, which says you should take h as small as possible. But as h gets smaller, the error from floating point subtraction increases since the numerator requires subtracting nearly equal numbers. If h is too small, you can loose a lot of precision in the subtraction. So in practice you have to pick a not-too-small value of h that minimizes the combination of approximation error and numerical error. As a rule of thumb, you can try h = SQRT(DBL_EPSILON) where DBL_EPSILON is the smallest double precision number e such that 1 + e != 1 in machine precision. DBL_EPSILON is about 10^-15 so you could use h = 10^-7 or 10^-8. For more details, see these notes on picking the step size for differential equations.
1,559,786
1,559,846
C++ GCC 4.3.2 error on vector of char-array
It is similar in problem to this bug Question about storing array in a std::vector in C++ but for a different reason (see below). For the following sample program in C++: #include <vector> int main(int c_, char ** v_) { const int LENGTH = 100; std::vector<char[LENGTH]> ca_vector; return 0; } GCC 4.2.3 compiles cleanly. GCC 4.3.2 emits the following errors: /usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4/bits/stl_construct.h: In function ‘void std::_Destroy(_Tp*) [with _Tp = char [100]]’: /usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4/bits/stl_construct.h:103: instantiated from ‘void std::_Destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = char (*)[100]]’ /usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4/bits/stl_construct.h:128: instantiated from ‘void std::_Destroy(_ForwardIterator, _ForwardIterator, std::allocator&) [with _ForwardIterator = char (*)[100], _Tp = char [100]]’ /usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4/bits/stl_vector.h:300: instantiated from ‘std::vector::~vector() [with _Tp = char [100], _Alloc = std::allocator]’ test.cpp:7: instantiated from here /usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4/bits/stl_construct.h:88: error: request for member ‘~char [100]’ in ‘* __pointer’, which is of non-class type ‘char [100]’ The reason apparently is this bit in include/g++-v4/bits/stl_construct.h template inline void _Destroy(_Tp* __pointer) { __pointer->~_Tp(); } which is called, I think, due to incorrect array-to-pointer-decay. My question is: Is there anything in language standard preventing storage of arrays in std::vector? Or is it just a bug in that special GCC version? I do believe that this should compile (i.e. 4.2.3 is correct). Thanks martin
Yes there is something in the standard stopping using arrays Using Draft C++98 Standard Section 23 Containers The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignabletypes. where components are various containers 20.1.3 includes the requirement that the type has to have a destructor. I think of it as a vector has to copy allocate and delete elements. How does C++ know to copy or delete a char[] ?
1,559,809
1,559,923
Multiple meshes in one vertex buffer?
Do I need to use one vertex buffer per mesh, or can I store multiple meshes in one vertex buffer? If so, should I do it, and how would I do it?
You can store multiple meshes in one vertex buffer. You may gain some performance by putting several small meshes in in one buffer. For really large meshes you should use seperate buffers. SetStreamSource lets you specify the vertex buffer offset for your current mesh. pRawDevice->SetStreamSource( 0, m_VertexBuffer->GetBuffer(), m_VertexBuffer->GetOffset(), m_VertexBuffer->GetStride() );
1,559,884
1,562,133
Convert three letter language code to language identifier (LANGID)
Is there some way in the Win32 API to convert a three letter language code, as returned by GetLocaleInfo() with LOCALE_SABBREVLANGNAME specified, to a corresponding LANGID or LCID? That is, going in "reverse" to what GetLocaleInfo() normally does? What I'm trying to do is to parse what kind of language a resource DLL is using, and so far, without touching anything about the DLL, going by the dll name with a format nameLNG.dll, where LNG is a three letter language code, seems to be the easiest method, assuming such a function exists. If this isn't easy to do, I guess Plan B is to give our language DLL's a version info resource, specify their respective cultures there, and later on in the application, read which cultures they use.
Unfortunately, there's no direct Win32 API that gives you a LANGID given a 3-letters abbreviation. It looks like CLanguageSupport is your friend today :-) It already implements your plan B to lookup the LANGID based on the contents of the version info resource. The piece of code you're looking for is int the function LANGID CLanguageSupport::GetLangIdFromFile(LPCTSTR pszFilename) Of course, the drawback is that you may have a mismatch between the version info and the DLL name. But you'd very quickly catch it during tests. And if you let a tool such as appTranslator create the DLLs for you, you're sure to be on the safe side.
1,560,033
1,562,335
Getting HTTP xml error response using cURL
I am currently using cURL to communicate to a cloud site... everything is going well except for an annoying issue. The issue is that I cannot get the site's xml response when there is an error. for example, when I use Wire Shark to check the transfer I can see that in the HTTP header that I'm getting which contains the error code; there is an XML data that contains in addition to the error code, a message that describes the code. I have tried many cURL options to try and get the XML but all my attempts failed. Could someone tell me how can I get the XML. please note that I'm using the cURL C APIs as my code is in c++ and moreover, I can get XML responses when the operation succeeds using my write callback function.
Set CURLOPT_FAILONERROR to 0. If this is set to 1, then any HTTP response >= 300 will result in an error rather than processing like you want.
1,560,176
1,560,199
C++ function pointer as a static member
I cannot figure the syntax to declare a function pointer as a static member. #include <iostream> using namespace std; class A { static void (*cb)(int a, char c); }; void A::*cb = NULL; int main() { } g++ outputs the error "cannot declare pointer to `void' member". I assume I need to do something with parentheses but void A::(*cb) = NULL does not work either.
I introduced a typedef, which made it somewhat clearer in my opinion: class A { typedef void (*FPTR)(int a, char c); static FPTR cb; }; A::FPTR A::cb = NULL;
1,560,351
1,560,475
To Disable the multimedia contents in IE
I need to disable the multimedia contents in IE Programatically. Is there any way my programming environment is VC++
I'm not quite sure what you mean here. MSDN has the registry settings for various IE options (such as ShowPictures) This page shows an example of creating a web browser control with extremely fine grained settings: The most complete C# Webbrowser wrapper control
1,560,977
1,561,009
Why isn't c++ offered as a code-behind language for asp.net?
I was curious why C++ isn't offered as a code-behind language for ASP.NET applications?
If you are interested, here's some interesting articles about how you could use managed C++ as your code-behind: http://www.codeproject.com/KB/mcpp/helloworldmc.aspx http://msdn.microsoft.com/en-us/magazine/cc301369.aspx
1,561,007
1,561,475
Error when have private copy ctor with public assignment operator
Can one of you explain why the following piece of code does not compile? #include <iostream> using namespace std; class Foo { public: Foo() { cout << "Foo::Foo()" << endl << endl; } Foo& operator=(const Foo&) { cout << "Foo::operator=(const Foo&)" << endl << endl; } private: Foo(const Foo& b) { *this = b; cout << "Foo::Foo(const Foo&)" << endl << endl; } }; int main() { Foo foo; foo = Foo(); } The error I receive: $ g++ -o copy_ctor_assign copy_ctor_assign.cc && ./copy_ctor_assign copy_ctor_assign.cc: In function 'int main()': copy_ctor_assign.cc:10: error: 'Foo::Foo(const Foo&)' is private copy_ctor_assign.cc:17: error: within this context Note: when I remove the private: keyword the code compiles but the copy ctor is never called. So why does it err when it's private? Not sure if it's important but I'm using: $ g++ --version g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44) Copyright (C) 2006 Free Software Foundation, Inc.
You are initializing a reference from temporary. The standard states: The temporary should be initialized (8.5.3 par 5)"using the rules for a non-reference copy initialization (8.5)". The copy construction is removed for the temporary (permitted by the standard. 12.8 par 5). However, the standard clearly states (12.2 par 1): "Even when the creation of the temporary object is avoided (12.8), all the semantic restrictions must be respected as if the temporary object was created. [Example: even if the copy constructor is not called, all the semantic restrictions, such as accessibility (clause 11), shall be satisfied. ]" (also, when looking for the right quote, found this duplicate :) Edit: adding relevant location from the standard
1,561,008
1,561,236
SideBySide error on another computer with MSVC++ 2005 installed
I'm having some strange issues building and running a project on another computer. It's a side-by-side error. Usually the cause is that c++ redistributable is not installed on the machine etc. However in this case the project is compiled on that machine. MSVC++ 2005 is installed, the runtimes should be there (I installed the runtime again for good measure anyway). Why is the linker referencing a runtime library that isn't available on the machine? I'm dynamically linking to runtime library. Any ideas on how to debug this issue? Thanks. EDIT I didn't want to start another post because it's related. Because of this DLL version mess, is this a good reason to statically link to runtime? Will I avoid all these problems? I don't see any advantages to dynamically link to runtime any more. I was under the impression that with DLL runtime you get the benefit of updates/bug fixes with new DLLs. However because of the SxS and manifests it ensures that it loads the specific version (old version) of the DLL anyway? So what's the point of dynamic runtime at all? Maybe a few kb of space saved because you're not embedding the re-used functions in all the dependent libraries. But compare this to the cost of your app won't run because some ancient runtime version is removed from the machine, isn't it worth it? Thanks again. Still tracing the original problems and will probably have to recompile every single library I'm using.
sxstrace will tell you exactly what is going on with respect to SxS. It will show what dlls are searched and how they are mapped to actual versions. Now, which runtime is loaded is coming from the manifest file that gets included in your project. Looking at the one you mention, it looks like the one from Visual2005, with no service pack. SP1 changed the crt to 8.0.50727.762 Some details on sxstrace on vista and XP Well, since you added a question to your question, let me add an answer to my answer: SxS will not necessarily load the version you specify inside your manifest. The SxS system keeps track of security fixes made to specific versions, e.g. and will change which version it loads even when you ask for a specific version. That said, if your program uses DLLs, and you want to share C objects (e.g. malloc'ed memory) between them, then your only option is the CRT DLL. It really depends what your constraints are.
1,561,183
1,561,192
C++ operator overloading, understanding the Google style guide
I am following a book to learn C++ (come from a python background). I've written this, which works: class CatalogueItem { public: CatalogueItem(); CatalogueItem(int item_code, const string &name, const string &description); ~CatalogueItem() {}; bool operator< (const CatalogueItem &other) const; ... private: ... }; ... list<CatalogueItem> my_list; // this is just me playing around CatalogueItem items[2]; items[0] = CatalogueItem(4, string("box"), string("it's a box")); items[1] = CatalogueItem(3, string("cat"), string("it's a cat")); my_list.push_back(items[0]); my_list.push_back(items[1]); my_list.sort(); The part I'm trying out is using the operator < to allow the list to sort itsself. This all seems good, but http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading seems to suggest avoiding doing this, which is exactly what the book says to do! ("In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container.") I understand "create equality and comparison functor types" to mean creating comparison functions, like the below one: bool my_comparison_function(const CatalogueItem &a, const CatalogueItem &b) { // my comparison code here } Is that what the style guide is referring to? Does anyone have an option as to which method is more "correct"? J
A functor type would be more like this: struct CatalogueItemLessThan { bool operator()(const CatalogueItem &a, const CatalogueItem &b) { } }; Then the usage would look like this: list<CatalogueItem> my_list; // this is just me playing around CatalogueItem items[2]; items[0] = CatalogueItem(4, string("box"), string("it's a box")); items[1] = CatalogueItem(3, string("cat"), string("it's a cat")); my_list.push_back(items[0]); my_list.push_back(items[1]); my_list.sort(CatalogueItemLessThan()); The main advantage of this, is that is allows you to decouple sorting from the object itself. You can now provide as many types of sorting as you want, and use them in different places. (For example, string can be sorted in lexical order, or case-insensitively, or "naturally". The advantage of using a functor as opposed to a loose function is that you can pass parameters into the comparison to modify how the functor should behave. In general, the Google style-guide is not really the best style guide out there (IMHO especially their taking exception to exceptions, but that's another discussion). If an object has an obvious sorting order, I often add in a default operator<. If later, there are extra sort orders I want to add, then I add in loose functions. If at a later time, I need to add parameters to the sort order, then I make them into functors. There's no sense in adding in complexity before it's needed.
1,561,243
1,561,274
What's the meaning of (int&) conversion in C++
float b = 1.0f; int i = (int)b; int& j = (int&)b; cout << i << endl; cout << j << end; Then the output of i was 1, and the output of j was 1065353216! It is a big surprise to me! So what is the true meaning of (int&) conversion?
This is the problem with a C-style cast. You have to look closely to see what you're getting. In your case "(int)" was a normal static cast. The value is converted to an int via truncation. In your case "(int&)" was a reinterpret cast. The result is an lvalue that refers to the memory location of b but is treated as an int. It's actually a violation of the strict aliasing rules. So, don't be surprized if your code won't work anymore after turning on all optimizations. Equivalent code with C++ style casts: float b = 1.0f; int i = static_cast<int>(b); int& j = reinterpret_cast<int&>(b); cout<<i<<endl; cout<<j<<end; Check your favorite C++ book on these kinds of casts.
1,561,370
1,561,387
How to get the length of IStream? C++
I'm creating an IStream as follow: IStream* stream; result = CreateStreamOnHGlobal(0, TRUE, &stream); Then I have a CImage object that I save to this stream: image->Save(stream, Gdiplus::ImageFormatBMP); I need to get the size of bytes written to this IStream. How can I do this? There is no Length or something like this in the IStream... thanks!
IStream::Stat should do what you want.
1,561,416
1,561,437
Get a Win32 program to request a debugger on startup?
We have a C++ Win32 application which spawns, using Qt's QProcess (undoubtedly a wrapper for CreateProcess()), a secondary 'slave' program. Unfortunately, when debugging the system with Visual Studio 2008, the debugger does not automatically attach to the spawned process. I know it's possible to programmatically trigger a debugger breakpoint with __debugbreak(), but is it possible for the slave program to throw up the 'Choose a Program to Debug This' window immediately on startup since at the moment we have to race to manually attach to the new process?
Use Image File Execution Options. You can specify the Visual Studio just-in-time debugger as the default debugger to attach to the process. If you're into using the command-line debuggers, you can use ntsd -o to automatically debug child processes as well.
1,561,469
1,562,180
Is there an alternative to inet_ntop / InetNtop in Windows XP?
I'm trying to compile beej's guide to network programming examples, but Windows XP doesn't have such a function. I'm using mingw, if it makes any difference.
If you're only dealing with IPv4 addresses, you can use inet_ntoa. It's available on Windows 2000 or later. Otherwise you'll have to either require Vista and later, or write your own inet_ntop function. You could also look at boost - the boost::asio has an inet_ntop implementation that works in Windows: boost::asio::detail::socket_ops::inet_ntop. You can see the source code here.
1,561,536
1,561,558
C++ program not moving past cin step for string input
I'm obviously not quite getting the 'end-of-file' concept with C++ as the below program just isn't getting past the "while (cin >> x)" step. Whenever I run it from the command line it just sits there mocking me. Searching through SO and other places gives a lot of mention to hitting ctrl-z then hitting enter to put through an end-of-file character on windows, but that doesn't seem to be working for me. That makes me assume my problem is elsewhere. Maybe defining x as a string is my mistake? Any suggestions about where I'm going wrong here would be great. Note: sorry for the lack of comments in the code - the program itself is supposed to take in a series of words and then spit back out the count for each word. #include <iostream> #include <string> #include <vector> #include <algorithm> #include <iomanip> using std::cin; using std::cout; using std::endl; using std::sort; using std::string; using std::vector; int main() { cout << "Enter a series of words separated by spaces, " "followed by end-of-file: "; vector<string> wordList; string x; while (cin >> x) wordList.push_back(x); typedef vector<string>::size_type vec_sz; vec_sz size = wordList.size(); if (size == 0) { cout << endl << "This list appears empty. " "Please try again." << endl; return 1; } sort(wordList.begin(), wordList.end()); cout << "Your word count is as follows:" << endl; int wordCount = 1; for (int i = 0; i != size; i++) { if (wordList[i] == wordList[i+1]) { wordCount++; } else { cout << wordList[i] << " " << wordCount << endl; wordCount = 1; } } return 0; }
If you're on windows ^Z has to come as the first character after a newline, if you're on a unixy shell then you want to type ^D.
1,561,620
1,561,713
Is it possible to use function pointers across processes?
I'm aware that each process creates it's own memory address space, however I was wondering, If Process A was to have a function like : int DoStuff() { return 1; } and a pointer typedef like : typedef int(DoStuff_f*)(); and a getter function like : DoStuff_f * getDoStuff() { return DoStuff; } and a magical way to communicate with Process B via... say boost::interprocess would it be possible to pass the function pointer to process B and call Process A's DoStuff from Process B directly?
No. All a function pointer is is an address in your process's address space. It has no intrinsic marker that is unique to different processes. So, even if your function pointer just happened to still be valid once you've moved it over to B, it would call that function on behalf of process B. For example, if you had ////PROCESS A//// int processA_myfun() { return 3; } // get a pointer to pA_mf and pass it to process B ////PROCESS B//// int processB_myfun() { return 4; } // This happens to be at the same virtual address as pA_myfun // get address from process A int x = call_myfun(); // call via the pointer x == 4; // x is 4, because we called process B's version! If process A and B are running the same code, you might end up with identical functions at identical addresses - but you'll still be working with B's data structures and global memory! So the short answer is, no, this is not how you want to do this! Also, security measures such as address space layout randomization could prevent these sort of "tricks" from ever working. You're confusing IPC and RPC. IPC is for communicating data, such as your objects or a blob of text. RPC is for causing code to be executed in a remote process.
1,561,629
1,561,898
What are some techniques or tools for profiling excessive code size in C/C++ applications?
I have a C++ library that generates much larger code that I would really expect for what it is doing. From less than 50K lines of source I get shared objects that are almost 4 MB and static archives pushing 9. This is problematic both because the library binaries are quite large, and, much worse, even simple applications linking against it typically gain 500 to 1000 KB in code size. Compiling the library with flags like -Os helps this somewhat, but not really very much. I have also experimented with GCC's -frepo command (even though all the documentation I've seen suggests that on Linux collect2 will merge duplicate templates anyway) and explicit template instantiation on templates that seemed "likely" to be duplicated a lot, but with no real effect in either case. Of course I say "likely" because, as with any kind of profiling, blind guessing like this is almost always wrong. Is there some tool that makes it easy to profile code size, or some other way I can figure out what is taking up so much room, or, more generally, any other things I should try? Something that works under Linux would be ideal but I'll take what I can get.
If you want to find out what is being put into your executable, then ask your tools. Turn on the ld linker's --print-map (or -M) option to produce a map file showing what it has put in memory and where. Doing this for the static linked example is probably more informative. If you're not invoking ld directly, but only via the gcc command line, you can pass ld specific options to ld from the gcc command line by preceding them with -Wl,.
1,561,767
1,561,863
error returning std::set<T>::iterator in template
I'm making a template wrapper around std::set. Why do I get error for Begin() function declaration? template <class T> class CSafeSet { public: CSafeSet(); ~CSafeSet(); std::set<T>::iterator Begin(); private: std::set<T> _Set; }; error: type ‘std::set, std::allocator<_CharT> >’ is not derived from type ‘CSafeSet’
Try typename: template <class T> class CSafeSet { public: CSafeSet(); ~CSafeSet(); typename std::set<T>::iterator Begin(); private: std::set<T> _Set; }; You need typename there because it is dependent on the template T. More information in the link above the code. Lot's of this stuff is made easier if you use typedef's: template <class T> class CSafeSet { public: typedef T value_type; typedef std::set<value_type> container_type; typedef typename container_type::iterator iterator_type; typedef typename container_type::const_iterator const_iterator_type; CSafeSet(); ~CSafeSet(); iterator_type Begin(); private: container_type _Set; }; On a side note, if you want to be complete you need to allow CSafeSet to do the same thing as a set could, which means using a custom comparer and allocator: template <class T, class Compare = std::less<T>, class Allocator = std::allocator<T> > class CSafeSet { public: typedef T value_type; typedef Compare compare_type; typedef Allocator allocator_type; typedef std::set<value_type, compare_type, allocator_type> container_type; typedef typename container_type::iterator iterator_type; typedef typename container_type::const_iterator const_iterator_type; // ... } And a last bit of advice, if you are going to create a wrapper around a class, try to follow the same naming conventions as where the class came from. That is, your Begin() should probably be begin() (And personally I think C before a class name is strange but that one is up to you :])
1,561,768
1,561,901
Porting c++ code from unix to windows
Hi i have to port some stuff written on c++ from unix bases os to windows visual studio 2008. The following code implements array data type with void ** - pointer to the data. struct array { int id; void **array; // store the actual data of the array // more members } When i compile with g++ on Unix it's ok but when i try with MSVS 2008 I get the error - error C2461: 'array' : constructor syntax missing formal parameters. When i change the member from 'array' to something else it works, so it seems that the compiler thinks that the member name 'array' is actually the constructor of the struct array. It's obviously not a good practice to name the member like the struct but it's already written that way. Can i tell the MSVS compiler to ignore this problem or i should rename all members that are the same as the struct name.
You are dealing with a bug in GCC compiler. C++ language explicitly prohibits having data members whose name is the same as the name of the class (see 9.2/13). MS compiler is right to complain about it. Moreover, any C++ compiler is required to issue a diagnostic message in this case. Since GCC is silent even in '-ansi -pedantic -Wall' mode, it is a clear bug in GCC. Revison: What I said above is only correct within the "classic" C++98 specification of C++ language. In the most recent specification this requirement only applies to static data members of the class. Non-static data members can now share the name with the class. I don't know whether this change is already in the official version of the revised standard though. That means that both compilers are correct in their own way. MS compiler sticks to the "classic" C++98 specification of the language, while GCC seems to implement a more recent one.
1,561,910
1,566,620
How to Draw pixel data taken from the backbuffer back to itself?
I'm working on a mobile application for Symbian 5th edition using OpenGLES. This application is a pretty standard 2D app, and I make no use of the DepthBuffer. I need to grab a snapshot of the display and then draw the very same snapshot back to the backbuffer. I'm using glReadPixels((GLint)0, (GLint)0, (GLint)nWidth-1, (GLint)nHeight-1, GL_RGB, GL_UNSIGNED_BYTE, m_pPixelData) in order to get the pixel data I need, but I'm rather new to OpenGLES and I don't know how to draw the data back to the backbuffer. (in OpenGL its easy using DrawPixels..) I've read that I should generate a texture from the data, so I did. But now I'm not sure how to draw this texture. Do I need to draw it as a texture of a Rectangular element ? if so than how am I suppose to define this rect ? ( the coordinates just doesn't make sense to me..) The display size is 480x640 and here is the code I want to use in order to draw the rect: glEnable(GL_TEXTURE_2D); //displayTex is my texture built out of the pixel data glBindTexture(GL_TEXTURE_2D, m_pESSharedData->displayTex); //Bottom glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex3f(-2.5f, -2.5f, 2.5f); glTexCoord2f(1.0f, 0.0f); glVertex3f(2.5f, -2.5f, 2.5f); glTexCoord2f(1.0f, 1.0f); glVertex3f(2.5f, -2.5f, -2.5f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-2.5f, -2.5f, -2.5f); glEnd(); Note that above code is something I've picked up along the way, and I think this is the outline of what I'm suppose to do. feel free to take me off this track. :) I thank you for your time.
You first need to make sure that the version of OpenGL-ES on Series60 5th edition can handle textures whose height and width aren't powers of 2. I would advise forum nokia for that kind of query. Shameless plug: Quick Recipes On Symbian OS contains a whole chapter explaining the basics of OpenGL-ES on Symbian OS. The 3D code samples are here.
1,562,010
1,562,032
How to find the length of an LPCSTR
I'm trying to convert an LPCSTR to an integer using atoi(), and to verify that the conversion occurred successfully I want to count the number of digits in the integer it produced and the original LPCSTR (it should contain nothing but integers) I'm having a hard time finding a good way to calculate the length of the LPCSTR. So far the only way seems to be just counting until I get to a '/0' Any suggestions for a better method? Thanks
Isn't that what strlen does?
1,562,182
1,562,218
memorystream - stringstream, string, others?
i am reading in a binary file via the usual c++/STL/iostream syntax. i am copying the whole content into an dynamically allocated char array and this works fine so far. but since i want to serve parts of the content as lines to another part of the program, i think it would be better/easier to stick to streams because i don't want to hack around with cstring functions and pointers. my question now is, how can i store the read in memory. in a stringstream? or in a string? which fits better? are there any advantages or disadvantages of one over the other? thanks in advance!
If you want to read from it as a stream, you might as well read directly from the file to the stringstream: std::stringstream data; data << input_file.rdbuf(); That reads the entire contents of 'input_file' into 'data'. You can read the data from there like you would any other stream.
1,562,421
1,562,602
Making a HANDLE RAII-compliant using shared_ptr with a custom deleter
I've recently posted a general question about RAII at SO. However, I still have some implementation issues with my HANDLE example. A HANDLE is typedeffed to void * in windows.h. Therefore, the correct shared_ptr definition needs to be std::tr1::shared_ptr<void> myHandle (INVALID_HANDLE_VALUE, CloseHandle); Example 1 CreateToolhelp32Snapshot: returns HANDLE and works. const std::tr1::shared_ptr<void> h (CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL), CloseHandle); As I use void in the definition (what is the correct way?) problems go on, when I try to call some more winapi commands with this pointer. They functionally work, but are ugly and I am sure that there has to be a better solution. In the following examples, h is a pointer which was created via the definition at the top. Example 2 OpenProcessToken: last argument is a PHANDLE. medium ugly with the cast. OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, (PHANDLE)&h); Example 3 Process32First: first argument is a HANDLE. REALLY ugly. Process32First(*((PHANDLE)&h), &pEntry); Example 4 simple comparison with a constant HANDLE. REALLY ugly. if (*((PHANDLE)&h) == INVALID_HANDLE) { /* do something */ } What is the correct way to create a proper shared_ptr for a HANDLE?
Example 1 is OK Example 2 is wrong. By blindly casting to PHANDLE, the shared_ptr logic is bypassed. It should be something like this instead: HANDLE h; OpenProcessToken(...., &h); shared_ptr<void> safe_h(h, &::CloseHandle); or, to assign to a pre-exising shared_ptr: shared_ptr<void> safe_h = .... { HANDLE h; OpenProcessToken(...., &h); safe_h.reset(h, &::CloseHandle); }//For extra safety, limit visibility of the naked handle or, create your own, safe, version of OpenProcessToken that returns a shared handle instead of taking a PHANDLE: // Using SharedHandle defined at the end of this post SharedHandle OpenProcess(....) { HANDLE h = INVALID_HANDLE_VALUE; ::OpenProcessToken(...., &h); return SharedHandle(h); } Example 3: No need to take these detours. This should be ok: Process32First(h.get(), ...); Example 4: Again, no detour: if (h.get() == INVALID_HANDLE){...} To make things nicer, you could typedef something like: typedef shared_ptr<void> SharedHandle; or better yet, if all handles are to be closed with CloseHandle(), create a SharedHandle class wrapping a shared_ptr and automatically providing the right deleter: // Warning: Not tested. For illustration purposes only class SharedHandle { public: explicit SharedHandle(HANDLE h) : m_Handle(h, &::CloseHandle){}; HANDLE get()const{return m_Handle.get();} //Expose other shared_ptr-like methods as needed //... private: shared_ptr<void> m_Handle; };
1,562,572
1,562,723
Better method to search array?
I have an array (nodes[][]) that contains values of effective distances that looks something like this: __ __ |1 0.4 3 | |0.4 1 0 | |3 3.2 1 ... | |0.8 4 5 | |0 0 1 | -- -- Where the first value, node[0][0] is the distance from node 0 to node 0 which is 1. So the distance from node 2 to node 1 is 3.2 (node[2][1]=3.2) I need, given a node column, to search through the rows to find the farthest distance, while not picking itself (node[1][1]) The method I was thinking to do something like this: int n=0; currentnode=0; //this is the column I am searching now if(currentnode==n) n++; best=node[n][currentnode]; nextbest=node[n++][currentnode]; if(nextbest>best) best=nextbest; else for(int x=n;x<max;x++) //max is the last column { if(currentnode==n) continue; nextbest=node[x][currentnode]; if(nextbest>best) best=nextbest; } I can't think of a better method to do this. I could use functions to make it shorter but this is GENERALLY what I am thinking about using. After this I have to loops this to go to the next column that the best distance returns and do this routine again.
You can simplify it quite a bit. A lot of your checks and temporary variables are redundant. Here's a small function that performs your search. I've renamed most of the variables to be a little more precise what their roles are. int maxDistance(int fromNode) { int max = -1; for (int toNode = 0; toNode < nodeCount; ++toNode) { if (fromNode != toNode && nodes[toNode][fromNode] > max) { max = node[toNode][fromNode]; } } return max; }
1,562,948
1,563,167
C++ overload resolution problem
I've got the following structure: struct A { A(); virtual ~A(); virtual void Foo() =0; }; struct E; struct F; struct B: public A { B(); virtual ~B(); virtual void Bar(E*) =0; virtual void Bar(F*) =0; }; struct C: public B { C(); virtual ~C(); void Bar(E*); }; struct D: public C { D(); virtual ~D(); void Foo(); void Bar(F*); }; struct E: public A { E(); virtual ~E(); void Foo(); /* ... */ }; struct F: public A { F(); virtual ~F(); void Foo(); /* ... */ }; template <class _Base> struct G: public _Base { G(const _Base &b) : _Base(b) {} virtual ~G() {} using _Base::Bar; // doesn't help /* ... */ }; When I'm trying to call Bar() on an object of type G<D> with a E*, I get the following compile-time error: error: no matching function for call to 'G<D>::Bar(E*&)' note: candidates are: virtual void D::Bar(F*) If I rename the declarations of (virtual) void Bar(F*), the code compiles fine and works as expected. Usage: typedef std::list<E*> EList; typedef std::list<F*> FList; EList es; FList fs; G<D> player(D()); es.push_back(new E); // times many fs.push_back(new F); // times many for(EList::iterator i0(es.begin()), i1(es.end()); i0 != i1; ++i0) { player.Bar(*i0); } for(FList::iterator i0(fs.begin()), i1(fs.end()); i0 != i1; ++i0) { player.Bar(*i0); } 1, What's wrong with multiple overloads of member functions taking different arguments? 2, Why can't the compiler tell the difference between them?
Only the versions of Bar in the most-derived class containing an override of Bar will be considered for overload resolution unless you add in using declarations. If you try struct D: public C { D(); virtual ~D(); void Foo(); void Bar(F*); using C::Bar; }; then it should work.
1,562,992
1,563,021
Best Way to Store a va_list for Later Use in C/C++
I am using a va_list to construct a string that is rendered. void Text2D::SetText(const char *szText, ...) This is all fine and good, but now the user has the ability to change the language while the application is running. I need to regenerate all the text strings and re-cache the text bitmaps after initialization. I would like to store the va_list and use it whenever the text needs to be generated. To give you some more background, this needs to happen in the case where the key string that I'm translating has a dynamic piece of data in it. "Player Score:%d" That is the key string I need to translate. I would like to hold the number(s) provided in the va_list for later use (outside the scope of the function that initializes the text) in the case that it needs to be re-translated after initialization. Preferably I would like to hold a copy of the va_list for use with vsnprintf. I've done some research into doing this and have found a few ways. Some of which I question whether it is a appropriate method (in terms of being stable and portable).
Storing the va_list itself is not a great idea; the standard only requires that the va_list argument work with va_start(), va_arg() and va_end(). As far as I can tell, the va_list is not guaranteed to be copy constructable. But you don't need to store the va_list. Copy the supplied arguments into another data structure, such as a vector (of void*, probably), and retrieve them later in the usual way. You'll need to be careful about the types, but that's always the case for printf-style functions in C++.
1,563,124
1,563,136
C++ Vector class as a member in other class
Please I have this code which gives me many errors: //Neuron.h File #ifndef Neuron_h #define Neuron_h #include "vector" class Neuron { private: vector<double>lstWeights; public: vector<double> GetWeight(); }; #endif //Neuron.cpp File #include "Neuron.h" vector<double> Neuron::GetWeight() { return lstWeights; } Could any one tell me what is wrong with it?
It's: #include <vector> You use angle-brackets because it's part of the standard library, "" with just make the compiler look in other directories first, which is unnecessarily slow. And it is located in the namespace std: std::vector<double> You need to qualify your vector in the correct namespace: class Neuron { private: std::vector<double>lstWeights; public: std::vector<double> GetWeight(); }; std::vector<double> Neuron::GetWeight() Made simpler with typedef's: class Neuron { public: typedef std::vector<double> container_type; const container_type& GetWeight(); // return by reference to avoid // unnecessary copying private: // most agree private should be at bottom container_type lstWeights; }; const Neuron::container_type& Neuron::GetWeight() { return lstWeights; } Also, don't forget to be const-correct: const container_type& GetWeight() const; // const because GetWeight does // not modify the class
1,563,218
1,563,274
Are there any IDE's or plugins to one that will expand/preprocess a macro and show their results inline without compiling?
Are there any IDE's or plugins to one that will expand/preprocess a macro and show their results inline without compiling? I've found a couple of other questions that are related, but they require compiling.
Most compilers offer you the option to do that. Different compilers will have different switches though. Consult your docs. For example, with Microsoft C++ compilers that would be /E /EP and /P command-line switches. They can be specified from within their IDE as well. These switches also disable compilation, just as you wanted.
1,563,311
1,563,327
How do I get a description of the current OS version in windows?
I need to get a simple description of the OS, such as "Windows XP (SP2)" or "Windows 2000 Professional" to include in some debugging code. Ideally, I'd like to simply retrieve it by calling a "GetOSDisplayName" function. Is there such a function available for C++ win32 programming?
Have a look at this: http://msdn.microsoft.com/en-us/library/ms724429(VS.85).aspx
1,563,409
1,563,658
Fastest implementation of one thread providing data, many threads consuming data
I have a lot of data that I want to disseminate to many different threads. This data is coming from a single thread. The consuming threads can safely access the container simultaneously. The data needs to be merged into the container ever delta seconds (50ms < delta < 1), during which time the consuming threads need to be locked out, but not blocked. Similarly, when the data producer wants to merge in the data, it should wait until any reading threads are finished (which should be fast), but no one else should start reading as the update needs to occur as soon as possible. I'm working on linux (platform specific solution is perfectly fine/expected) and I care about every millisecond. What sort of locking mechanisms should I use or is there an even better model for this problem?
If there is only one data producer thread and memory is not a consideration, you may want to consider using a merge and swap algorithm. In it, the writer thread creates a copy of the data structure while readers continue to use the original, merges in new changes, then performs an exchange of the two structures within a mutex or critical section (or reader/writer lock). If your Unix platform supports interlocked exchange as an atomic operation, you can perform a lock-free exchange maximizing read throughput through they implementation.
1,563,491
1,578,871
What is the recommended design for public-facing APIs to support multiple POD types while maximizing binary compatibility?
I am currently designing a public-facing C++ API for a product which will require a pre-compiled binary/DLL (it will be cross-platform). I would like for the API to allow the user to use any POD we support (where applicable), however the base requirements are maximum flexibility and binary compatibility. I am doing something a bit similar to CPLEX's API (it's one of several inspirations), but I'm thinking there's possibly a better way of specifying type information than how they have done it (with respect to IloInt, IloNum, IloAny, Ilo*Var, etc., see link (hopefully) for IloExtractable branch) without messing with binary compatibility. Am I wrong? I've got something in mind, but I can't recall what it is or if it'll even work, I believe it resembles something like the Visitor or Decorator patterns but for types, could someone please enlighten me on the subject? I've got my Design Patterns book by the GoF out in front of me. Note: any syntax errors there might be here aren't part of the problem at hand. Examples of what I believe I can't use, and the reason: Possibly.. but this is likely to make things complicated with the Expression tree. template<typename ValueType> Constraint : public Expression; Probably will impact future expansion. IntConstraint : public Expression; LongConstraint : public Expression; DoubleConstraint : public Expression; Ugly as sin, may cause plenty of subtle issues. union Value { int AsInt, float AsFloat }; class Constraint : public Expression { public: Value GetValue(Edge); void SetValue(Value, Edge); void SetUpper(Value, Vertex); void SetLower(Value, Vertex); ... }; Edit: In response to Mads Elvheim (and after finding this link) I now realize that I don't need to exclude templates from my possibilities which is good, but I am still rather unsure it's the best idea - at least for the Constraints class (even though it's conceptually sound), forgive me for not being as clear as I thought. In order to make my API easy to use I defined the grammar using bnf (which is rather new to me). This led to an abstract syntax tree for Expression, Constraints, and other classes which will be included which interact with Constraints. Because other classes will be interacting with Constraints, I would prefer avoiding passing as munch type information as possible until "the last minute" so to speak.. I feel like I may be missing a level of abstraction. Studying CPLEX gives me the impression that they modeled their types by following the domains of numbers (whole and real), linear equation expression (of course) and what should accordingly be possible, which absolutely makes sense, hmm... (Apparently I can't post more than one link as I'm a new user.) Edit 2: As a first step I've decided to stick a ConstraintExpressionArgument in between the Constraint and Expression classes so I can still identify a constraint in my expression tree without being aware of the type it manipulates which is good. Another detail I may have neglected to mention was that unlike in CPLEX where the Constraint class is unusable by itself, my Constraint class is currently a usable user class but like in CPLEX I also want to leave room for expansion (thus the typing issue)... Anyway, at the moment I have the equivalent of class ConstraintExpressionArgument : public Expression; template<typename ValueType> class Constraint : public ConstraintExpressionArgument;
Right, I think I've got what I need, at least for now. The above mentioned class ConstraintExpressionArgument : public Expression; template<typename ValueType> class Constraint : public ConstraintExpressionArgument; got me on the right track to separating type from constraint-ness.
1,563,700
1,563,717
Compression Libraries For C++
I was reading about compression in programs and I started to create a new simple project, a zipper (just a zipper, not an unzipper), but I only found zLib, and it's for C. I know that C libraries can be used in C++, but I like to use C++ libraries. Does anyone know a good one to suggest? Best Regards.
Most compression libraries that I know of are written in C for two reasons: one, the general age of good compression algorithms; and two, the high portability (and stability) of C across platforms. I suggest any of the following. If you want good licenses select one of the top two, otherwise if you're open to using GPL code pick one of the last two. Bzip2 Zlib LZO UCL
1,563,704
1,563,711
VS2008: how to run two separate projects from the same solution
I have a single un-managed C++ console-app solution (.sln) with two projects (.vcproj) both are built as .exe. I want to run them both at the same time (one is a client and one is a server). How do I configure my Visual Studio such that when I hit a single button, say F5, it would be smart enough to run one after another, in the order that I specify? Currently what I have to do is set one project to be a "Startup project" then hit "Ctrl+F5" to run one, then I have to change the "Startup project" to be the other one, then hit "Ctrl+F5". Indeed, doing this 25 times a day is painful. =p
Right-click on the solution in Solution Explorer, click Properties (If the window is blank, select the solution again), and go to the Startup Projects section under Common Properties. Select the Multiple Startup Projects option. Then, you can specify which project(s) to launch and whether each one should have the debugger attached. You can use the up and down arrows to change the launch order.
1,563,774
1,563,795
Help interpret this stack trace
I know that it fails at strcmp. I've provided operator< below, which calls strcmp. On line #1 there's the value @0xbfffeeac. What does the @ mean? #0 0x00212bd8 in strcmp () from /lib/libc.so.6 #1 0x0012ed2f in Json::Value::CZString::operator< (this=0x8317300, other=@0xbfffeeac) at src/lib_json/json_value.cpp:221 #2 0x001361b0 in std::less<Json::Value::CZString>::operator() (this=0x83173a0, __x=@0x8317300, __y=@0xbfffeeac) at /usr/lib/gcc/i586-redhat-linux/4.4.1/../../../../include/c++/4.4.1/bits/stl_function.h:230 #3 0x00136101 in std::_Rb_tree<Json::Value::CZString, std::pair<Json::Value::CZString const, Json::Value>, std::_Select1st<std::pair<Json::Value::CZString const, Json::Value> >, std::less<Json::Value::CZString>, std::allocator<std::pair<Json::Value::CZString const, Json::Value> > >::_M_lower_bound (this=0x83173a0, __x=0x83172f0, __y=0x83173a4, __k=@0xbfffeeac) at /usr/lib/gcc/i586-redhat-linux/4.4.1/../../../../include/c++/4.4.1/bits/stl_tree.h:986 #4 0x001348da in std::_Rb_tree<Json::Value::CZString, std::pair<Json::Value::CZString const, Json::Value>, std::_Select1st<std::pair<Json::Value::CZString const, Json::Value> >, std::less<Json::Value::CZString>, std::allocator<std::pair<Json::Value::CZString const, Json::Value> > >::find (this=0x83173a0, __k=@0xbfffeeac) at /usr/lib/gcc/i586-redhat-linux/4.4.1/../../../../include/c++/4.4.1/bits/stl_tree.h:1421 #5 0x0013383a in std::map<Json::Value::CZString, Json::Value, std::less<Json::Value::CZString>, std::allocator<std::pair<Json::Value::CZString const, Json::Value> > >::find (this=0x83173a0, __x=@0xbfffeeac) at /usr/lib/gcc/i586-redhat-linux/4.4.1/../../../../include/c++/4.4.1/bits/stl_map.h:659 #6 0x00131779 in Json::Value::operator[] (this=0x8317280, key=0xbfffef74 "col1") at src/lib_json/json_value.cpp:1055 #7 0x00131ba8 in Json::Value::isMember (this=0x8317280, key=0xbfffef74 "col1") at src/lib_json/json_value.cpp:1169 #8 0x0805cf4d in CFG::CFG_Fetch_Raw (this=0x825846c, section=0x8317280, key=0xbfffef74 "col1", defval=0x0) at CFG.cpp:48 #9 0x08050e5b in Generic::CFGSetup (this=0x825846c, k=0x8255e2c "display_qt") at Generic.cpp:89 #10 0x0804df6a in LCDControl::ConfigSetup (this=0xbffff2a8) at LCDControl.cpp:81 #11 0x0804d93b in LCDControl::Start (this=0xbffff2a8, argc=1, argv=0xbffff404) at LCDControl.cpp:15 #12 0x0804f224 in main (argc=1, argv=0xbffff404) at Main.cpp:7 bool Value::CZString::operator<( const CZString &other ) const { if ( cstr_ ) return strcmp( cstr_, other.cstr_ ) < 0; //src/lib_json/json_value.cpp:221 return index_ < other.index_; }
You're checking this->cstr_ for null, but you're not checking other.cstr_. Perhaps the container prevents any strings with null cstr_ values from being inserted, so such a check is not necessary. That's not the problem, however, since other is not null in this case. Rather it looks like the other object may have been deleted. How are you managing the lifetimes of the objects in the std::map container? Is it possible that one of the values was deleted without being removed from the map? Update: On further inspection, this seems to be the key: #5 0x0013383a in std::map<...>::find (this=0x83173a0, __x=@0xbfffeeac) #6 0x00131779 in Json::Value::operator[] (this=0x8317280, key=0xbfffef74 "col1") You're passing in a constant string pointer (0xbfffef74, which is obviously valid since the debugger displays the string), and it's being automatically converted into a temporary value of type CZString. You can see that the temporary CZString object is faithfully passed all the way down to the operator<. I believe that the 0x8... addresses indicate heap allocations, while 0xbf... addresses indicate stack allocations. Unfortunately, what we need to see is the arguments to strcmp(). We need to know if, when CZString::operator< was called with an "other" argument of 0xbfffeeac (the temporary CZString object), whether it passed the original string value of 0xbfffef74 into strcmp, or perhaps a heap-allocated copy of that string (I don't know what CZString does internally). If this is the first comparison in the b-tree search, that probably indicates that the second argument to strcmp was not correctly converted to a CZString. Otherwise, it indicates that the second argument is being passed down correctly, and one of the strings in your map is invalid but not null, leaving "deleted" and "not null-terminated" as likely suspects.
1,563,897
1,563,906
Static constant string (class member)
I'd like to have a private static constant for a class (in this case a shape-factory). I'd like to have something of the sort. class A { private: static const string RECTANGLE = "rectangle"; } Unfortunately I get all sorts of error from the C++ (g++) compiler, such as: ISO C++ forbids initialization of member ‘RECTANGLE’ invalid in-class initialization of static data member of non-integral type ‘std::string’ error: making ‘RECTANGLE’ static This tells me that this sort of member design is not compliant with the standard. How do you have a private literal constant (or perhaps public) without having to use a #define directive (I want to avoid the uglyness of data globality!) Any help is appreciated.
You have to define your static member outside the class definition and provide the initializer there. First // In a header file (if it is in a header file in your case) class A { private: static const string RECTANGLE; }; and then // In one of the implementation files const string A::RECTANGLE = "rectangle"; The syntax you were originally trying to use (initializer inside class definition) is only allowed with integral and enum types. Starting from C++17 you have another option, which is quite similar to your original declaration: inline variables // In a header file (if it is in a header file in your case) class A { private: inline static const string RECTANGLE = "rectangle"; }; No additional definition is needed.
1,564,119
1,564,127
More vs Less Functions
I had a little argument, and was wondering what people out there think: In C++ (or in general), do you prefer code broken up into many shorter functions, with main() consisting of just a list of functions, in a logical order, or do you prefer functions only when necessary (i.e., when they will be reused very many times)? Or perhaps something in between?
Small functions, please It is the conventional wisdom that smaller functions are better, and I think it's true. In fact, there is a company with an analysis tool that rates individual functions by how many decisions they make compared to the number of unit tests that they have. The theory is that you may or may not be able to reduce complexity in an entire application, but you have complete control over how much complexity is in any given function. A measurement called cyclomatic complexity is thought to correlate positively with bad code...specifically, the more paths there are through a method the higher its CCN number is, the more poorly it is written, the harder it is to understand and hence change or even get right to start with, and the more unit tests it will need. Ok, found the tool. It is called, ahem, the Change Risk Analysis and Predictions index. Lately, the principle of encoding information only once has grown new acronyms, specifically DRY (Don't Repeat Yourself) and DIE (Duplication is Evil) ... I believe we can in part thank the RoR community for promoting this philosophy...
1,564,240
1,564,285
Polymorph collection in C++
I need to code a class that recieves a collection with any number of elements of any 'primitive' type. I also need to be able to know the type of each member (or at least the size of the type). The purpose of this class is to serialize the elements to store them in a file in fixed length registers. Is this posible? I know that C++ is statically typed and that there's no common parent regarding inheritance (such as Object in Java). So, I cannot recieve an array or a vector, as all the elements should have the same type. I also thought of an array of pointers, but in such way I wouldn't know the elements type or its size. Any ideas? PS: couldn't find similar question, but if it exists, please redirectme.
Have you looked into boost::any ? It sounds like it might be a good match for your problem: storing a polymorphic collection of objects, without the loss of type information that occurs with arrays of void * or similar hacks.
1,564,668
1,564,790
cmake and eclipse: default include paths?
I have a project that builds with CMake system, and I like to import it in Eclipse. However, when I generate eclipse project files with 'cmake -G "Eclipse CDT4 - Unix Makefiles"' there are no default include paths in Eclipse project(such as /usr/include' or the gcc path for standard headers). How to fix that in most right way? System: linux gcc 4.3.3 cmake 2.6.4 eclipse 3.5.1
You have to go to the project properties (right button over the project), "C/C++ include paths and symbols" and add them here as "external include paths".
1,564,802
1,564,813
How to work (portably) with C++ class hierarchies & dynamic linked libraries
Ok, so I know portability is not the strong point of C++, but I have to get my code running on both Mac&Windows. I've come up with a solution, but it's not perfect, and I'm interested to see if there is someone out there who can suggest a better one. I need to us a class hierarchy in several DLLs/bundles - e.g., I have an abstract base class BaseClass; and I scan a given directory for DLLs, and for each DLL, I look for the factory method BaseClass* CreateObject(); - which returns a "BaseClass". I have a "shared header file" that I include both in the "main executable" & in the DLLs, that declares the BaseClass like this #ifdef _MAC #define DECLSPEC #else #ifdef COMPILING_DLL #define DECLSPEC __declspec(dllexport) #else #define DECLSPEC __declspec(dllimport) #endif #endif class DECLSPEC BaseClass{ [.. base "interface" declaration .. ] } And then, in my DLL, I would typically include the BaseClass declaration, and declare my own "concrete" class: class MyDllClass:public BaseClass{ [.. actual DLL class definition/implementation here goes here ...] } So far, so good. Now for some reason, I need to differentiate in my main executable between two different kinds of BaseObjects - say I have a DescriptionClass and an ActionClass, both of which are BaseClass, but have a slightly different interface. My fist implementation was to simply do modify the "shared header" and add: class DECLSPEC DescriptionClass{ [.. base "Description interface" declaration .. ] } class DECLSPEC ActionClass{ [.. base "Action interface" declaration .. ] } Then my DLL would become: class MyDllClass:public ActionClass /* or DescriptionClass, depending on case*/ { [.. actual DLL class definition/implementation here goes here ...] } And in my main executable, I would use it like this: BaseClass* obj = CreateObjectFromDLL("path_to_dll"); ActionClass* action_obj = dynamic_cast<ActionClass*>(obj); if(action_obj){ // Do the stuff that is relevant for Action objects } DescriptionClass* description_obj = dynamic_cast<ActionClass*>(obj); if(description_obj){ // Do the stuff that is relevant for Description objects } And herein lies the problem: although it works on Windows with Visual Studio (probably due to the MS declspec extension), it fails on Mac (not sure now if it fails on Debug, but I'm sure it fails on release) when compiled with GCC. The reason is simple, even if not immediately obvious: the executable & the dynamic library are compiled separately. Although they both include the declaration of BaseClass, ActionClass, DescriptionClass - these classes are not the same, they are just "identical copies" that are present in the binary and the DLL. So actually, what I'm creating in the DLL is a dll'BaseClass* , which happens to have the same memory layout with main'Baseclass*, so the pointers are compatible, so when I pass the pointer from DLL to EXE, it all works "as expected". OTOH, when I go to a more complex class hierarchy, the vtables/RTTI of dll'ActionClass and main'ActionClass are no longer identical (although in source code they are identical), so when I try do convert (through dynamic_cast) a main'BaseClass* to a main'ActionClass* i get a null result -> because my pointer actually points to a dll'BaseClass object / dll'ActionClass object, and alghough in the DLL I can convert with no proble a "BaseClass*" into a "ActionClass*" - in the main executable, I can't convert the dll's "BaseClass*" into a "ActionClass*", due to the subtle runtime differences between the DLL's and the "main executable's" version of Action Class. I've "fixed" this by declaring a virtual method in the BaseClass (something like "bool isActionClass()" ), so now I can differentiate... but I'm not very happy with this solution. Is there something for GCC - e.g. some declaration similar to "__declspec" - a way to guarantee that the same class declared in "main executable" and in "dll" will be 100% compatible?
I actually found the answer to my question due to the fact that I needed to formulate it completely, and I did a better google search :) It seems to be __attribute__((dllimport)) // import __attribute__((dllexport)) // export Will try that, I thought I'd leave the question here too, in case someone else stumbles on this problem (and as a warning to people that same header file included in a "main binary" & DLL will normaly lead to different actual implementation, depending on the compiler options - unless you put the proper dllimport/export attributes on the class).
1,564,817
1,564,854
Declare but not define inner struct/class - legal C++ or not?
Is following code legal C++ or not? class Foo { class Bar; void HaveADrink(Bar &bar); void PayForDrinks(Bar &bar); public: void VisitABar(int drinks); }; class Foo::Bar { public: int countDrinks; }; void Foo::HaveADrink(Bar &bar) { bar.countDrinks++; } void Foo::PayForDrinks(Bar &bar) { bar.countDrinks = 0; } void Foo::VisitABar(int drinks) { Bar bar; for (int i=0; i<drinks; i++) HaveADrink(bar); PayForDrinks(bar); } Both Visual C++ and GCC accepts it, however the code seems somewhat strange to me and I would hate to have it refused by some future compiler. Still, the pattern seems useful to me to reduce compile time dependencies - I often use it to declare structs which are used to pass some "context" (a bunch of variables) which are shared between a few functions which all reside in the same cpp file, and this way I do not have to introduce the "context" definition into the public interface.
legal, and indeed usefull to hide implementation details to the outside world.
1,564,824
1,564,845
C++ Overloading << Operator problem
I'm fairly noobish at C++, but very comfortable with pointers, dereferencing, etc. I'm having a problem with my overload of the << operator for a class, in that it compiles fine but crashes when run. It feels like an infinite loop, but I'm not certain. Here's the code, and any help is appreciated. #include <string> #include <iostream> using namespace std; class Person { private: string _name; Person* _manager; public: Person(string name, Person *manager); Person(string name); friend ostream &operator<<(ostream &stream, Person &p); }; Person::Person(string name, Person *manager) { _name = name; _manager = manager; } Person::Person(string name) { _name = name; } ostream &operator<<(ostream &stream, Person &p) { Person* mgr = p._manager; stream << p._name << std::endl; stream << mgr->_name << std::endl; return stream; } int main() { Person *pEmployee = new Person("John Doe Employee"); Person *pManager = new Person("John Doe Manager", pEmployee); cout << *pEmployee; cout << *pManager; return 0; }
In your constructor with just a single argument, you need to set _manager to NULL/0. Test for this in your operator<< and don't output mgr->name if it is NULL/0. As it stands, you are dereferencing an uninitialised pointer. Person::Person(string name) { _name = name; _manager = 0; } ostream &operator<<(ostream &stream, Person &p) { Person* mgr = p._manager; stream << p._name << std::endl; if (mgr) stream << mgr->_name << std::endl; return stream; } There are a number of other things you could do better, such as using const references on arguments and using the constructor initialiser list, but they wont be the cause of your problem. You should also address ownership issues with the manager object you pass in to the constructor to ensure it does not get double-deleted.
1,564,870
1,564,882
Recommended OpenGL / GLUT Reference
What OpenGL / GLUT reference is good for day to day programming as you learn? Ideally I'm looking for something with lots of C++ sample code to help me learn as I develop OpenGL applications as well as details about the APIs similar to what MSDN provides for .net programming. If there isn't a one stop shop, then please list the set of references I should use and what the strengths of each one is.
The Red Book is the standard book on OpenGL. Don't be discouraged by the fact that the Amazon review for the 7th Edition has only two stars; this is because people are disappointed that there isn't more on the newest OpenGL features in the book. Previous editions got more stars. Another good book is the OpenGL SuperBible. The NeHe Tutorials are one of the most often cited OpenGL tutorials, with sample code not only in C++ but in many other programming languages.
1,565,065
1,565,089
A Polymorphism Problem
it works when : list<ItemFixed> XYZ::List() { list<Item> items = _Browser->GetMusic(); list<ItemFixed> retItems = _Converter->Convert (items); return retItems; } but not : list<ItemFixed> XYZ::List() { return _Converter->Convert (_Browser->GetMusic()); } Any suggestions? thanks
Are you passing the list<Item> as non-const reference to Convert function? In that case it will not compile as you can not pass temporary object by non-const reference in C++.
1,565,406
1,567,751
C++ LINQ-like iterator operations
Having been tainted by Linq, I'm reluctant to give it up. However, for some things I just need to use C++. The real strength of linq as a linq-consumer (i.e. to me) lies not in expression trees (which are complex to manipulate), but the ease with which I can mix and match various functions. Do the equivalents of .Where, .Select and .SelectMany, .Skip and .Take and .Concat exist for C++-style iterators? These would be extremely handy for all sorts of common code I write. I don't care about LINQ-specifics, the key issue here is to be able to express algorithms at a higher level, not for C++ code to look like C# 3.0. I'd like to be able to express "the result is formed by the concatenation first n elements of each sequence" and then reuse such an expression wherever a new sequence is required - without needed to manually (and greedily) instantiate intermediates.
I don't have concrete experience with LINQ, but the Boost.Iterator library seems to approach what you're referring to. The idea is to have functions (IIUC, in LINQ, they take the form of extension methods, but that's not fundamental), taking an iterator and a function, combining them to create a new iterator. LINQ "Where" maps to make_filter_iterator: std::vector<int> vec = ...; // An iterator skipping values less than "2": boost::make_filter_iterator(_1 > 2, vec.begin()) LINQ "Select" maps to make_transform_iterator: using namespace boost::lambda; //An iterator over strings of length corresponding to the value //of each element in "vec" //For example, 2 yields "**", 3 "***" and so on. boost::make_transform_iterator(construct<std::string>('*', _1), vec.begin()) And they can be composed: //An iterator over strings of length corresponding to the value of each element // in "vec", excluding those less than 2 std::vector<int> vec = ...; boost::make_transform_iterator(construct<std::string>('*', _1), boost::make_filter_iterator(_1 > 2, vec.begin()) ) However, there are a few annoying things with this: The type returned by make_xxx_iterator(some_functor, some_other_iterator) is xxx_iterator<type_of_some_functor, type_of_some_iterator> The type of a functor created using boost::bind, lambda, or phoenix quickly becomes unmanageably large and cumbersome to write. That's why I avoided in the code above to assign the result of make_xxx_iterator to a variable. C++0x "auto" feature will be pretty welcome there. But still, a C++ iterator can't live "alone": they have to come in pairs to be useful. So, even with "auto", it's still a mouthful: auto begin = make_transform_iterator(construct<std::string>('*', _1), make_filter_iterator(_1 > 2, vec.begin()) ); auto end = make_transform_iterator(construct<std::string>('*', _1), make_filter_iterator(_1 > 2, vec.end()) ); Avoiding the use of lambda makes things verbose, but manageable: struct MakeStringOf{ MakeStringOf(char C) : m_C(C){} char m_C; std::string operator()(int i){return std::string(m_C, i);} }; struct IsGreaterThan{ IsGreaterThan(int I) : m_I(I){} int m_I; bool operator()(int i){return i > m_I;} }; typedef boost::filter_iterator< IsGreaterThan, std::vector<int>::iterator > filtered; typedef boost::transform_iterator< MakeStringOf, filtered > filtered_and_transformed; filtered_and_transformed begin( MakeStringOf('*'), filtered(IsGreaterThan(2), vec.begin()) ); filtered_and_transformed end( MakeStringOf('*'), filtered(IsGreaterThan(2), vec.end()) ); The (not-yet)Boost.RangeEx library is promising in this respect, in that it allows to combine the two iterators in a single range. Something like: auto filtered_and_transformed = make_transform_range( make_filter_range(vec, _1 > 2), construct<std::string>('*', _1) );
1,565,517
1,565,720
Dynamically created scope guards
I've read the article about scope guards (Generic: Change the Way You Write Exception-Safe Code — Forever) in DDJ and I understand their common use. However, the common use is to instantiate a particular stack guard on the stack for a particular operation, e.g.: { FILE* topSecret = fopen("cia.txt"); ON_BLOCK_EXIT(std::fclose, topSecret); ... use topSecret ... } // topSecret automagically closed but what if I want to schedule cleanup operations in runtime, e.g. when I have a loop: { vector<FILE*> topSecretFiles; for (int i=0; i<numberOfFiles; ++i) { char filename[256]; sprintf(filename, "cia%d.txt", i); FILE* topSecret = fopen(filename); topSecretFiles.push_back(topSecret); ON_BLOCK_EXIT(std::fclose, topSecret); // no good } } Obviously, the above example wouldn't work, since topSecret would be closed along with the for scope. I'd like a scope guard pattern where I can just as easily queue up cleanup operations which I determine to be needed at runtime. Is there something like this available? I can't push scope guard objects into a standard queue, cause the original object (the one I'm pushing) would be dismissed in the process. How about pushing heap-allocated stack guards and using a queue which deletes its members on dtor? Does anyone have a more clever approach?
It seems you don't appreciate RAII for what it is. These scope guards are nice on occasion for local ("scope") things but you should try to avoid them in favour of what RAII is really supposed to do: encapsulating a resource in an object. The type FILE* is really just not good at that. Here's an alternative: void foo() { typedef std::tr1::shared_ptr<FILE> file_sptr; vector<file_sptr> bar; for (...) { file_sptr fsp ( std::fopen(...), std::fclose ); bar.push_back(fsp); } } Or: void foo() { typedef std::tr1::shared_ptr<std::fstream> stream_sptr; vector<stream_sptr> bar; for (...) { file_sptr fsp ( new std::fstream(...) ); bar.push_back(fsp); } } Or in "C++0x" (upcoming C++ standard): void foo() { vector<std::fstream> bar; for (...) { // streams will become "movable" bar.push_back( std::fstream(...) ); } } Edit: Since I like movable types in C++0x so much and you showed interest in it: Here's how you could use unique_ptr in combination with FILE* without any ref-counting overhead: struct file_closer { void operator()(FILE* f) const { if (f) std::fclose(f); } }; typedef std::unique_ptr<FILE,file_closer> file_handle; file_handle source() { file_handle fh ( std::fopen(...) ); return fh; } int sink(file_handle fh) { return std::fgetc( fh.get() ); } int main() { return sink( source() ); } (untested) Be sure to check out Dave's blog on efficient movable value types
1,565,567
1,565,590
In which scenario it is useful to use Disassembly language while debugging
I have following basic questions : When we should involve disassembly in debugging How to interpret disassembly, For example below what does each segment stands for 00637CE3 8B 55 08 mov edx,dword ptr [arItem] 00637CE6 52 push edx 00637CE7 6A 00 push 0 00637CE9 8B 45 EC mov eax,dword ptr [result] 00637CEC 50 push eax 00637CED E8 3E E3 FF FF call getRequiredFields (00636030) 00637CF2 83 C4 0C add Language : C++ Platform : Windows
It's quite useful to estimate how efficient is the code emitted by the compiler. For example, if you use an std::vector::operator[] in a loop without disassembly it's quite hard to guess that each call to operator[] in fact requires two memory accesses but using an iterator for the same would require one memory access. In your example: mov edx,dword ptr [arItem] // value stored at address "arItem" is loaded onto the register push edx // that register is pushes into stack push 0 // zero is pushed into stack mov eax,dword ptr [result] // value stored at "result" address us loaded onto the register push eax // that register is pushed into stack call getRequiredFields (00636030) // getRequiredFields function is called this is a typical sequence for calling a function - paramaters are pushed into stack and then the control is transferred to that function code (call instruction). Also using disassembly is quite useful when participating in arguments about "how it works after compilation" - like caf points in his answer to this question.
1,565,600
1,565,811
How come a non-const reference cannot bind to a temporary object?
Why is it not allowed to get non-const reference to a temporary object, which function getx() returns? Clearly, this is prohibited by C++ Standard but I am interested in the purpose of such restriction, not a reference to the standard. struct X { X& ref() { return *this; } }; X getx() { return X();} void g(X & x) {} int f() { const X& x = getx(); // OK X& x = getx(); // error X& x = getx().ref(); // OK g(getx()); //error g(getx().ref()); //OK return 0; } It is clear that the lifetime of the object cannot be the cause, because constant reference to an object is not prohibited by C++ Standard. It is clear that the temporary object is not constant in the sample above, because calls to non-constant functions are permitted. For instance, ref() could modify the temporary object. In addition, ref() allows you to fool the compiler and get a link to this temporary object and that solves our problem. In addition: They say "assigning a temporary object to the const reference extends the lifetime of this object" and " Nothing is said about non-const references though". My additional question. Does following assignment extend the lifetime of temporary object? X& x = getx().ref(); // OK
From this Visual C++ blog article about rvalue references: ... C++ doesn't want you to accidentally modify temporaries, but directly calling a non-const member function on a modifiable rvalue is explicit, so it's allowed ... Basically, you shouldn't try to modify temporaries for the very reason that they are temporary objects and will die any moment now. The reason you are allowed to call non-const methods is that, well, you are welcome to do some "stupid" things as long as you know what you are doing and you are explicit about it (like, using reinterpret_cast). But if you bind a temporary to a non-const reference, you can keep passing it around "forever" just to have your manipulation of the object disappear, because somewhere along the way you completely forgot this was a temporary. If I were you, I would rethink the design of my functions. Why is g() accepting reference, does it modify the parameter? If no, make it const reference, if yes, why do you try to pass temporary to it, don't you care it's a temporary you are modifying? Why is getx() returning temporary anyway? If you share with us your real scenario and what you are trying to accomplish, you may get some good suggestions on how to do it. Going against the language and fooling the compiler rarely solves problems - usually it creates problems. Edit: Addressing questions in comment: 1) `X& x = getx().ref(); // OK when will x die?` - I don't know and I don't care, because this is exactly what I mean by "going against the language". The language says "temporaries die at the end of the statement, unless they are bound to const reference, in which case they die when the reference goes out of scope". Applying that rule, it seems x is already dead at the beginning of the next statement, since it's not bound to const reference (the compiler doesn't know what ref() returns). This is just a guess however. I stated the purpose clearly: you are not allowed to modify temporaries, because it just does not make sense (ignoring C++0x rvalue references). The question "then why am I allowed to call non-const members?" is a good one, but I don't have better answer than the one I already stated above. Well, if I'm right about x in X& x = getx().ref(); dying at the end of the statement, the problems are obvious. Anyway, based on your question and comments I don't think even these extra answers will satisfy you. Here is a final attempt/summary: The C++ committee decided it doesn't make sense to modify temporaries, therefore, they disallowed binding to non-const references. May be some compiler implementation or historic issues were also involved, I don't know. Then, some specific case emerged, and it was decided that against all odds, they will still allow direct modification through calling non-const method. But that's an exception - you are generally not allowed to modify temporaries. Yes, C++ is often that weird.
1,565,654
1,566,149
Qt Map Signals Based On Parameter Value
I know that i can use QSignalMapper to call a slot with different parameters based on connection. What i want to achieve is a little different. We are using plugins in our application and different plugins are responsible for different types of objects. We are connecting multiple slots, each implemented in a different plugin, to one signal emitted by the main application. One of the parameters of the signal is a QString indicating the type of object associated with the signal. Currently, we are checking this parameter in the slots and proceed if the type is handled by the plugin. This has a downside, every plugin does this checking and i want to avoid this if possible. I want to connect all slots to the same signal, and when the signal is emitted, only the appropriate slot is called depending on the value of the QString argument, kind of like a QSignalMapper but in a different way. Is there any built-in mechanism to do this? If not, any ideas on how i can achieve this? Thank you in advance.
I don't think there's a component for that, but you could create your own signal mapper like this: create a MySignalMapper component code an addSourceSignal method to set the signal of the main app code an addDestinationSlot method that takes a QString/slot pair and maps the string to the slot. in your component connect the source signal to a custom slot that dispatches based on the qstring value. You can invoke a slot with QMetaObject::invokeMethod.
1,565,724
1,565,727
Clarification on lists and removing elements
If I have a list<object*>>* queue and want to pop the first object in the list and hand it over to another part of the program, is it correct to use (sketchy code): object* objPtr = queue->first(); queue->pop_first(); return objPtr; // is this a pointer to a valid memory address now? ? According to the documentation on http://www.cplusplus.com/reference/stl/list/pop_front/ it calls the destructor of the deleted element, but I'm confused as to whether it means the linked list's node object, or the actually stored "user" object. Edit: I might be front instead of first, my bad.
Yes, it is a valid pointer. List will not release the memory allocated by you. List will destroy its internal not the user object.
1,566,178
1,566,191
Preprocessor definitions going haywire. int define redefinition?
I am trying to add a preprocessor definition so that a value is only defined while a certain project is building, then it becomes undefined. I have gone into my project properties -> preprocessor -> preprocessor definitions. In here, I typed #define PROJECTNAME_EXPORT, in hopes that I could call #ifdef PROJECTNAME_EXPORT throughout that project to swap out a value (between dllexport and dllimport) on build-time. However, when I hit okay, it looks like visual studio adds a double quote before my definition. When I try to build, I get over 100 errors, mostly saying "illegal escape sequence". Others of note are "int define: redefinition", "int MYPROJECT_EXPORT redefinition", etc. Have I done something wrong?
You don't include the "#define" in the definition. Just the name of the symbol, and optionally a value, like so: PROJECTNAME_EXPORT=coolness The way to think of the definitions you enter here, into the IDE, is that they will be passed to the compiler using the /D option, so the syntax ought to be close. There would be no need to include the #define syntax, since these definitions are handed to the compiler/preprocessor not in C source, but through a different mechanism.
1,566,198
1,566,222
How to (portably) get DBL_EPSILON in C and C++
I am using GCC 3.4 on Linux (AS 3) and trying to figure out to get DBL_EPSILON, or at least a decent approximation. How can I get it programmatically?
It should be in "float.h". That is portable, it's part of the C and C++ standards (albeit deprecated in C++ - use <cfloat> or sbi's answer for "guaranteed" forward compatibility). If you don't have it, then since your doubles are IEEE 64-bit, you can just steal the value from someone else's float.h. Here's the first one I found: http://opensource.apple.com/source/gcc/gcc-937.2/float.h #define DBL_EPSILON 2.2204460492503131e-16 The value looks about right to me, but if you want to be sure on your compiler, you could check that (1.0 + DBL_EPSILON) != 1.0 && (1.0 + DBL_EPSILON/2) == 1.0 Edit: I'm not quite sure what you mean by "programmatically". It's a standard constant, you aren't supposed to calculate it, it's a property of the implementation given to you in a header file. But I guess you could do something like this. Again, assuming IEEE representation or something like it, so that DBL_EPSILON is bound to be whatever power of 0.5 represents a 1 in the last bit of precision of the representation of 1.0: double getDblEpsilon(void) { double d = 1; while (1.0 + d/2 != 1.0) { d = d/2; } return d; } Beware that depending on compiler settings, intermediate results might have higher precision than double, in which case you'd get a smaller result for d than DBL_EPSILON. Check your compiler manual, or find a way to force the value of 1.0 + d/2 to be stored and reloaded to an actual double object before you compare it to 1.0. Very roughly speaking, on PCs it depends on whether your compiler uses the x86 FPU instructions (higher precision), or newer x64 floating point ops (double precision).
1,566,241
1,566,269
How to get the name of an Event from a handle
I have an array of Win32 event handles that I'm waiting on using WaitForMultipleObjects(). This returns the index in the array of events that triggered but what I need to know is the name of the event. I've been looking through MSDN and can't see anything to do this. Basically I have a class that monitors the registry through events using RegNotifyChangeKeyValue() for a defined period of time but before it starts other classes register there interest in keys and values. I then wait on a separate thread and report back the name of the keys that have been modified. The event name is the key that the event is for and I don't know until runtime how many of these there will be or what they will be called. I don't want to create one thread per key as it's not very performant. Does anyone know how to get the event name or a better way of doing this?
Personally I wouldn't do it that way. Create your own mapping (std::map?) between event and key name and then do your own lookup when an event is signalled.
1,566,394
1,566,413
Close LogonUser Handle if Failed Logon?
The LogonUser function http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx returns a handle that you can use to impersonate the user, when you are done using it you call CloseHandle to close it. My question is, do you need to close the handle if the logon attempt fails (ie wrong username or password)?
No. LogonUser returns zero if it fails and no handle is created. Though, if you do call CloseHandle on it, CloseHandle should just return ERROR_INVALID_HANDLE.
1,566,445
1,566,501
Accessing a method from a templated derived class without using virtual functions in c++?
How do I get around this? I clearly cannot make the value() method virtual as I won't know what type it is beforehand, and may not know this when accessing the method from b: class Base { public: Base() { } virtual ~Base() { } private: int m_anotherVariable; }; template <typename T> class Derived : public Base { public: Derived(T value) : m_value(value) { } ~Derived() { } T value() { return m_value; } void setValue(T value) { m_value = value; } private: T m_value; }; int main() { Base* b = new Derived<int>(5); int v = b->value(); return 0; } Compilation errors: error: 'class Base' has no member named 'value'
This statement: int v = b->value(); The variable 'b' is being trated like it is an object of Derived<int>. So tell the compiler: int v = dynamic_cast<Derived<int>*>(b)->value(); Note: If b is not a Derived<int> the result of the cast is NULL. So the following would probably be safer: Derived<int>* d = dynamic_cast<Derived<int>*>(b); if (d) { int v = d->value(); } else { // Error } Alternatively by using references you get a bad_cast exception thrown: // Throw bad_cast on failure. Derived<int>& d = dynamic_cast<Derived<int>&>(*b); int v = d->value(); Or to be nice and obscrure we can do it one line. // Assign v or throw bad_cast exception: int v = dynamic_cast<Derived<int>&>(*b).value(); But I think you can achieve what you are trying to do with the boost::any int main() { boost::any b(5); int v = boost::any_cast<int>(b); b = 5.6; // double double d = boost::any_cast<double>(b); }
1,566,603
1,566,650
What is being done in this bit shifting operation?
(INBuffer[3] << 8) + INBuffer[2] Is this essentially moving the bit in INBuffer[3] into INBuffer[2] or [3] being zero'ed out then added to [2]?
This is a simple way to make a 16 bit value from two 8 bit values. INBuffer[3] = 0b01001011; INBuffer[2] = 0b00001001; INBuffer[3]<<8 // 0b0100101100000000; (INBuffer[3]<<8) + INBuffer[2] // 0b0100101100001001 Usually this is represented as (INBuffer[3]<<8) | INBuffer[2];
1,566,612
1,566,715
Is a cgi different from a console application?
I am having some problems in running cgi on my Apache (Windows, XAMPP), but the exe runs smoothly on the command prompt. Reading the logs on Apache folder it gives no information about the error. Any ideas about this?
Weird. I found the problem, it was in a sprintf("%f", f); where f wasn't initiated. This is weird, because it ran normal on my cmd but not on apache any clues?
1,566,793
1,590,281
WNetAddConnection2 in Windows 7 with Impersonation and no Error Code
I'm doing some crazy impersonation stuff to get around UAC dialogs in Windows 7 so the user does not have to interact with the UI (I have the admin creds of course). I have a process running as the Administrator and elevated past UAC. The issue that I'm facing is that when I make a call to WNetAddConnection2, within this process, I am not getting a new mapped net drive. The function returns ERROR_SUCCESS but no net drive is visible. We have another method of adding network drives using 'subst' but this, again, returns successful does does not add a net drive. I have tried to use the default user (which is the Administrator because of process's security context) and I have tried using specific user credentials. I can map the drive just fine through Explorer. Of course the same functionality works fine in XP/2003. I haven't got around to testing on Vista because of issues with impersonation that are limiting my ability to spin up the process. Are there unique Windows 7 limits on this function? MSDN does not glean any that I can find. Any help would be greatly appreciated!
The issue was that the process was running as Administrator. Impersonation will not work because WNetAddConnection2 evaluates on processes user. You must start a separate process to accomplish this.
1,566,862
1,566,924
Difference between variable-length argument and function overloading
This C++ question seems to be pretty basic and general but still I want someone to answer. 1) What is the difference between a function with variable-length argument and an overloaded function? 2) Will we have problems if we have a function with variable-length argument and another same name function with similar arguments?
2) Do you mean the following? int mul(int a, int b); int mul(int n, ...); Let's assume the first multiplies 2 integers. The second multiplies n integers passed by var-args. Called with f(1, 2) will not be ambiguous, because an argument passed through "the ellipsis" is associated with the highest possible cost. Passing an argument to a parameter of the same type however is associated with the lowest possible cost. So this very call will surely be resolved to the first function :) Notice that overload resolution only compares argument to parameter conversions for the same position. It will fail hard if either function for some parameter pair has a winner. For example int mul(int a, int b); int mul(double a, ...); Imagine the first multiplies two integers, and the second multiplies a list of doubles that is terminated by a 0.0. This overload set is flawed and will be ambiguous when called by mul(3.14, 0.0); This is because the second function wins for the first argument, but the first function wins for the second argument. It doesn't matter that the conversion cost for the second argument is higher for the second function than the cost of the first argument for the first function. Once such a "cross" winner situation is determined, the call for such two candidates is ambiguous.
1,566,895
1,566,937
LNK2019 when converting an app to use DLLs
(Re-written for clarity) I have a multi-project solution that I am looking to convert from using .lib to .DLL files. I have created my __declspec macros and applied it to every class except for those in the project that creates the final .exe. The linker is throwing a fit on just about everything, however. I have set up to ignore errors about exporting templated objects. One example is this: error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall Rail::SetNextRail(class Rail *)" (__imp_?SetNextRail@Rail@@QAEXPAV1@@Z) referenced in function "public: static void __cdecl MyUtilities::CreateBezierRails(int,class MyVector *,class std::vector > &)" (?CreateBezierRails@MyUtilities@@SAXHPAVMyVector@@AAV?$vector@PAVRail@@V?$allocator@PAVRail@@@std@@@std@@@Z) MyUtilities.obj Unresolved external symbol on my __declspec(dllimport)? That doesn't seem right. It is getting placed by a macro such as: #ifdef MYAI_EXPORT #define DECLSPECAI __declspec(dllexport) #else #define DECLSPECAI __declspec(dllimport) #endif Basically, what gives? Why am I getting these errors and how can I fix them? Thank you to everybody who has tried to help thus far, but I am still stuck with this.
Are you linking against MyRenderer.lib?
1,567,138
1,567,186
"const T &arg" vs. "T arg"
Which of the following examples is the better way of declaring the following function and why? void myFunction (const int &myArgument); or void myFunction (int myArgument);
Use const T & arg if sizeof(T)>sizeof(void*) and use T arg if sizeof(T) <= sizeof(void*)
1,567,167
1,567,243
How do I set a specific printer for a report?
I want to print a customized report to a specific printer, bypassing the print dialog. The printer is to be selected by the user for each report template. Right now I have the code to print the report showing the print dialog, or directly to the default printer. I need to change it in order to print directly to a printer which is not necessarily the default one. I realize that calling SetDefaultPrinter before printing is an easy solution, but it's not thread-safe. Note: I'm using C++/MFC.
Another article from Microsoft's KB: How to programmatically print to a non-default printer in MFC
1,567,282
1,567,380
use of extern methods between dll projects?
I have a debug condition to manage memory where I have extern void* operator new(unsigned int size, const char* file, int line); extern void operator delete(void* address, const char* file, int line); extern void Delete(void* address); #define FUN_NEW new(__FILE__, __LINE__) #define FUN_DELETE delete This exists in Memory.h and is implemented in Memory.cpp. Memory.h is defined as: #ifdef MEMORY_EXPORT #define DECL_MEMORY __declspec(dllexport) #else #define DECL_MEMORY __declspec(dllimport) #endif class DECL_MEMORY Memory : public Singleton<Memory> { Now, I have SoundStuff.h and SoundStuff.cpp, which are in a seperate project, also being converted to a dll in a similar manner to above. The project that SoundStuff belongs to has a project dependency to the project that Memory belongs to. In the implementation of SoundStuff.cpp, FUN_DELETE, from Memory.h, is called. It is called through a function in a separate project, but it is called regardless. This is leading to linker errors. error LNK2019: unresolved external symbol "void __cdecl operator delete(void *,char const *,int)" (??3@YAXPAXPBDH@Z) referenced in function __unwindfunclet$?Init@SoundStuff@@AAEXXZ$1 SoundStuff.obj Why is this and how can I fix it?
You have to explicitly tell the compiler which functions you'd like to export. There's a little song-and-dance to do this, here's how I do it: #ifdef USING_DLL #ifdef CORE_EXPORTS #define CORE_EXPORT __declspec( dllexport ) #else #define CORE_EXPORT __declspec( dllimport ) #endif #else #define CORE_EXPORT #endif Each function (or class) I would like to export gets tagged with CORE_EXPORT. To build for DLLs, define USING_DLL, and in your CoreFunctions project (but not your DoSomeStuff project) define CORE_EXPORTS. That will ensure that your functions/classes are declared __declspec( dllexport ) when the CoreFunctions DLL is building (so they are exported), and __declspec( dllimport ) when DoSomeStuff is building (so they are imported).
1,567,336
1,567,487
Simple 'for' loop crashing program on final iteration
The below program seems to be crashing at the very end each time, and I'm assuming that this is because once I get to i = (size-1) then wordList[i+1] won't return anything, returns null, or something equivalent. Any way around this? Am I correct that this is the source of my problem? #include <iostream> #include <string> #include <vector> #include <algorithm> #include <iomanip> using std::cin; using std::cout; using std::endl; using std::sort; using std::string; using std::vector; // Obtain a list of words and return the de-duped list // with an accompanying word count int main() { cout << "Enter a series of words separated by spaces, " "followed by end-of-file: "; vector<string> wordList; string x; while (cin >> x) wordList.push_back(x); typedef vector<string>::size_type vec_sz; vec_sz size = wordList.size(); if (size == 0) { cout << endl << "This list appears empty. " "Please try again." << endl; return 1; } sort(wordList.begin(), wordList.end()); cout << "Your word count is as follows:" << endl; int wordCount = 1; for (int i = 0; i != size; i++) { if (wordList[i] == wordList[i+1]) { wordCount++; } else { cout << wordList[i] << " " << wordCount << endl; wordCount = 1; } } return 0; }
You need two changes. As stated in previous comments, your for ending condition should be < size-1 to prevent reading out of bounds. You also need to print the count of the last item, which will be wordCount because if it's unique wordCount is 1 and if not it has been already added. Corrected code: for (int i = 0; i < size-1; i++) { if (wordList[i] == wordList[i+1]) { wordCount++; } else { cout << wordList[i] << " " << wordCount << endl; wordCount = 1; } } cout << wordList[size-1] << " " << wordCount << endl;
1,567,388
1,567,551
Boost C++ date_time microsec_clock and second_clock
I discovered a strange result in Boost C++ date time library. There is inconsistency between microsec_clock and second_clock, and I don't understand why is that. I am using Windows XP 32-bits My snip of code: using namespace boost::posix_time; ... ptime now = second_clock::universal_time(); std::cout << "Current Time is: "<< to_iso_extended_string(now)<< std::endl; ptime now_2 = microsec_clock::universal_time(); std::cout << "Current Time is: "<< to_iso_extended_string(now_2)<< std::endl; ... The print-out I expected are current time without miliseconds and with milliseonds. However, what I have in my pc is: 2009-10-14T16:07:38 1970-06-24T20:36:09.375890 I don't understand why there is a weired date (year 1970???) in my microsec_clock time. Related documentation for Boost: link to boost date time
Not sure what could be wrong for you; the exact same code works for me. $ cat > test.cc #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace boost::posix_time; int main() { ptime now = second_clock::universal_time(); std::cout << "Current Time is: "<< to_iso_extended_string(now)<< std::endl; ptime now_2 = microsec_clock::universal_time(); std::cout << "Current Time is: "<< to_iso_extended_string(now_2)<< std::endl; return 0; } ^D $ c++ -lboost_date_time test.cc $ ./a.out Current Time is: 2009-10-14T16:26:55 Current Time is: 2009-10-14T16:26:55.586295 Implementation-wise, second_clock uses time and microsec_clock uses gettimeofday or GetSystemTimeAsFileTime underneath, depending on the platform. Something appears wrong with your platform -- what is your OS and version? What is your Boost version? If it is 1.38 or lower, upgrade to 1.39 or apply the fix to #2809 manually. --- boost/date_time/filetime_functions.hpp (revision 53621) +++ boost/date_time/filetime_functions.hpp (revision 53622) @@ -96,9 +96,7 @@ { /* shift is difference between 1970-Jan-01 & 1601-Jan-01 * in 100-nanosecond intervals */ - const uint64_t c1 = 27111902UL; - const uint64_t c2 = 3577643008UL; // issues warning without 'UL' - const uint64_t shift = (c1 << 32) + c2; + const uint64_t shift = 116444736000000000ULL; // (27111902 << 32) + 3577643008 union { FileTimeT as_file_time; Windows FileTime has a different offset from UNIX time, and the code that was in Boost before would not generate the correct offset difference in certain optimizing compilers.
1,567,557
1,567,595
How to fix heap corruption
I've tried to build a very minimalistic memory read library to read some unsigned ints out of it. However, I run into a "HEAP CORRUPTION DETECTED" error message when the ReadUnsignedInt method wants to return. HEAP CORRUPTION DETECTED. CRT detected that the application wrote to memory after end of buffer. As I have read, this may be the cause when trying to double delete something. This may be caused by some incorrect usage of the std::tr1::shared_ptr but I cannot determine what I am doing wrong with them. Code is as follows (error handling omitted): unsigned int Memory::ReadUnsignedInt (unsigned int address) const { std::tr1::shared_ptr<byte> bytes = this->ReadBytes(address, sizeof(unsigned int)); return *((int*)bytes.get()); // correct value (how to improve this ugly piece of code?) } std::tr1::shared_ptr<byte> Memory::ReadBytes ( unsigned int address, int numberOfBytes) const { std::tr1::shared_ptr<byte> pBuffer(new byte(numberOfBytes)); ReadProcessMemory(m_hProcess.get(), (LPCVOID)address, pBuffer.get(), numberOfBytes * sizeof(byte), NULL)) return pBuffer; }
Michael and Naveen have both found the same major flaw in your code, but not the only flaw. shared_ptr will delete the pointed-at object when its reference count goes to zero. This means you can only give it objects allocated by new -- not new[]. You may wish to use shared_ptr<vector<byte> > or boost::shared_array<byte> instead.
1,567,650
1,567,690
How to fix a C1010 error without turning off precompiled headers?
So, I have to use precompiled headers in my VS 2005 project. Now I have a shared source file that does not have a #include "stdafx.h"... How can I include the shared source file in my project without adding stdafx.h to the top of the source file and without turning off precompiled headers??
File properties -> C/C++ -> Precompiled Headers -> Create/Use precompiled headers -> Not using ...
1,567,738
1,567,774
Linking error: Missing symbol but symbol exported (in exp and lib)
I have a dynamic library (plugin) that uses another dynamic library (dependency). I use the dependency in two ways: a. by instantiating object from classes defined in the dependency b. by inheriting from classes defined in the dependency When doing a., there are no linking errors. But when doing b., I have a linking error stating that I am missing some symbols (LNK2001). I looked in the .lib/.exp for the exact mangled name and did find the symbol that MSVC (2005) says is missing. It might be important to say that I use Qt and that the missing symbols are symbols that are automatically generated in the moc files (staticMetaObject of the parent class). Also, it might be relevant to say that I get these errors in both debug and release, which means that they are not "optimized away" (I even tried /OPT:NOREF /OPT:NOICF, although its the default in debug builds and that the symbols are in the lib file...) How can I have this linking error even though the symbols are in there? And most importantly, how can I fix these errors? Thanks for any help!
You might want to make sure the class is being declared with __declspec(dllexport) (when building) and __declspec(dllimport) (when linking against)? See this link.
1,567,834
1,568,044
Why is the compiler not selecting my function-template overload in the following example?
Given the following function templates: #include <vector> #include <utility> struct Base { }; struct Derived : Base { }; // #1 template <typename T1, typename T2> void f(const T1& a, const T2& b) { }; // #2 template <typename T1, typename T2> void f(const std::vector<std::pair<T1, T2> >& v, Base* p) { }; Why is it that the following code always invokes overload #1 instead of overload #2? int main() { std::vector<std::pair<int, int> > v; Derived derived; f(100, 200); // clearly calls overload #1 f(v, &derived); // always calls overload #1 return 0; } Given that the second parameter of f is a derived type of Base, I was hoping that the compiler would choose overload #2 as it is a better match than the generic type in overload #1. Are there any techniques that I could use to rewrite these functions so that the user can write code as displayed in the main function (i.e., leveraging compiler-deduction of argument types)?
You can either do this: f(v, static_cast<Base*>(&derived)); Or use SFINAE to remove the first function as a selection candidate: // Install boost library and add these headers: #include <boost/utility/enable_if.hpp> #include <boost/type_traits.hpp> // #1 - change it to look like this (note the keyword void changed positions) template <typename T1, typename T2> typename boost::disable_if< typename boost::is_convertible<T2, Base*>, void>::type f(const T1& a, const T2& b) { }; // #2 - this one can stay the same template <typename T1, typename T2> void f(const std::vector<std::pair<T1, T2> >& v, Base* p) { };
1,567,960
1,568,016
C++ Parent class method call
I'm creating a new class that inherits queue from the STL library. The only addition to the class is a vector. This vector will have the same size of the queue and it will store some integer values that will correspond to each objects in the queue. Now, I want to override pop() and push(), but I simply want to add more functionality to the parent's class methods. ex. When pop() is called on the queue object, I also want pop an object from the vector. When push() is called on the queue object, I also want insert a new object into the vector. How do I do that??? #include <iostream> #include <iostream> #include <queue> #include <vector> using namespace std; template <typename type> class CPU_Q : public queue<type> { public: vector<int> CPU_TIME; void increaseTime() { for(int ndx = 0; ndx < CPU_TIME.size(); ndx++) { CPU_TIME[ndx]++; } } void push(type insertMe) { //This is what I want to do super::push(); // or queue::push(); maybe? CPU_TIME.push_back(0); } void pop() { //Something very similar to push() } } Many Many thanks in advance -Tri
You asked about: void push(type insertMe){ //This is what I want to do super::push(); // or queue::push(); maybe? CPU_TIME.push_back(0); } That would be more like: void push(type insertMe) { queue<type>::push(insertMe); CPU_TIME.push_back(0); } Except you probably want to accept the parameter by const reference: void push(type const &insertme) { queue<type>::push(insertMe); CPU_TIME.push_back(0); } That said, the standard container classes aren't really designed for inheritance (e.g. they don't have a virtual dtors), so you'll have to be careful with this -- e.g. when you destroy it, you'll need the static type to be the derived type; you'll get undefined behavior if (for example) you destroy one via a pointer to the base class.
1,567,972
1,568,193
'operator new': redefinition, different linkage (using _dllspec on redefined new operator)
I am using __declspec(dllimport/export) on a debug version of new as such: #ifdef _DEBUG DECLSPECCORE extern void* operator new(unsigned int size, const char* file, int line); extern void* operator new[](unsigned int size, const char* file, int line); extern void operator delete(void* address, const char* file, int line); extern void operator delete[](void* address, const char* file, int line); extern void Delete(void* address); #define LUDO_NEW new(__FILE__, __LINE__) #define LUDO_DELETE delete #endif This is causing me to get error C2375: 'operator new': redefinition; different linkage. Why is this and how can you fix it? This is the only project that I am compiling right now.
If you have two two prototypes of overloading the new operator you must export both. Hopefulyl that is your problem.
1,568,298
1,568,326
Under what conditions will you get unresolved external symbol for __declspec(dllimport)?
I am converting an application to use .dlls and I'm riddled with linker errors stating unersolved external symbol"__declspec(dllimport) public: void __thiscall Rail::SetNextrail(class Rail *)" There is more gibberish at the end of this error message. Why should this happen and how do you fix it? __declspec(dllimport) is being placed with a macro defined as: #ifdef LUDOAI_EXPORT #define DECLSPECAI __declspec(dllexport) #else #define DECLSPECAI __declspec(dllimport) #endif
I believe what you need to do is specify the Rails "import library" to the linker. Using the GUI, this is on the linker tab of project settings, under "additional libraries." The "import library" is a .LIB file which contains symbols that resolve to the imports of the corresponding library. In the symbols from the .LIB file is an unconditional jump to the imports table's corresponding address for the import. When your code calls an import, it really calls this stub in the import library, which jumps to the import.
1,568,377
1,568,866
Convert RGB IplImage to 3 arrays
I need some C++/pointer help. When I create an RGB IplImage and I want to access i,j I use the following C++ class taken from: http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html template<class T> class Image { private: IplImage* imgp; public: Image(IplImage* img=0) {imgp=img;} ~Image(){imgp=0;} void operator=(IplImage* img) {imgp=img;} inline T* operator[](const int rowIndx) { return ((T *)(imgp->imageData + rowIndx*imgp->widthStep));} }; typedef struct{ unsigned char b,g,r; } RgbPixel; typedef struct{ float b,g,r; } RgbPixelFloat; typedef Image<RgbPixel> RgbImage; typedef Image<RgbPixelFloat> RgbImageFloat; typedef Image<unsigned char> BwImage; typedef Image<float> BwImageFloat; I've been working with CUDA so sometimes I have to put all the data into an array, I like to keep every channel in its own array, seems easier to handle the data that way. So I would usually do something like this: IplImage *image = cvLoadImage("whatever.tif"); RgbImageFloat img(image); for(int i = 0; i < exrIn->height; i++) { for(int j = 0; j < exrIn->width; j++) { hostr[j*data->height+i] = img[i][j].r; hostg[j*data->height+i] = img[i][j].g; hostb[j*data->height+i] = img[i][j].b; } } I would then copy my data to the device, do some stuff with it, get it back to the host and then loop, yet again, through the array assigning the data back to the IplImage and saving my results. It seems like I'm looping to much there has to be a faster way to do this with pointers but I'm lost, there has to be a more efficient way to do it. Is there a way I can simply use a pointer for every channel? I tried doing something like this but it didn't work: float *hostr = &img[0][0].r float *hostg = &img[0][0].b float *hostb = &img[0][0].g Any suggestions? Thanks! EDIT: Thanks everyone for answering. Maybe I wasn't very clear on my question. I am familiar on how to access channels and their data. What I am interested is in increasing the performance and efficiency of completely copying data off the IplImage to a standard array, more along the lines of what csl said so far. The problem I see is that the way data in an IplImage is arranged is "rgbrgbrgbrgb".
Firstly, if you're comfortable with C++, you should consider using OpenCV 2.0 which does away with different data types for images and matrices (IplImage* and CvMat*) and uses one structure (Mat) to handle both. Apart from automatic memory management and a truckload of useful routines to handle channels, etc. and some MATLAB-esque ones as well, it's really fun to use. For your specific problem, you access the channels of an IplImage* with Mat, like this: IplImage *image = cvLoadImage("lena.bmp"); Mat Lena(image); vector<Mat> Channels; split(Lena,Channels); namedWindow("LR",CV_WINDOW_AUTOSIZE); imshow("LR",Channels[0]); waitKey(); Now you have the copies of each channel in the vector Channels. If you don't want to use OpenCV2.0 and extract channels, note the following. OpenCV orders multi-channel images in the following manner: x(1,1,1) x(1,1,2) x(1,1,3) x(1,2,1) x(1,2,2) x(1,2,3) ... where x(i,j,k) = an element in row i of column j in channel k Also, OpenCV pads it's images .. so don't forget to jump rows with widthStep which accounts for these padding gaps. And along the lines of what csl said, increase your row pointer in the outer loop (using widthStep) and increment this pointer to access elements in a row. NOTE: Since you're using 2.0 now, you can bypass IplImage* with Mat Lena = imread("Lena.bmp");.
1,568,419
1,568,495
Should I implement my own TCP/IP socket timeouts?
The software I'm working on needs to be able to connect to many servers in a short period of time, using TCP/IP. The software runs under Win32. If a server does not respond, I want to be able to quickly continue with the next server in the list. Sometimes when a remote server does not respond, I get a connection timeout error after roughly 20 seconds. Often the timeout comes quicker. My problem is that these 20 seconds hurts the performance of my software, and I would like my software to give up sooner (after say 5 seconds). I assume that the TCP/IP stack (?) in Windows automatically adjusts the timeout based on some parameters? Is it sane to override this timeout in my application, and close the socket if I'm unable to connect within X seconds? (It's probably irrelevant, but the app is built using C++ and uses I/O completion ports for asynchronous network communication)
On Linux you can int syncnt = 1; int syncnt_sz = sizeof(syncnt); setsockopt(sockfd, IPPROTO_TCP, TCP_SYNCNT, &syncnt, syncnt_sz); to reduce (or increase) the number of SYN retries per connect per socket. Unfortunately, it's not portable to Windows. As for your proposed solution: closing a socket while it is still in connecting state should be fine, and it's probably the easiest way. But since it sounds like you're already using asynchronous completions, can you simply try to open four connections at a time? If all four time out, at least it will only take 20 seconds instead of 80.
1,568,540
1,574,791
How to make gcc or ld report undefined symbols but not fail?
If you compile a shared library with GCC and pass the "-z defs" flag (which I think just gets passed blindly on to ld) then you get a nice report of what symbols are not defined, and ld fails (no .so file is created). On the other hand, if you don't specify "-z defs" or explicitly specify "-z nodefs" (the default), then a .so will be produced even if symbols are missing, but you get no report of what symbols were missing if any. I'd like both! I want the .so to be created, but I'd also like any missing symbols to be reported. The only way I know of to do this so far is to run it twice, once with "-z defs" and once without. This means the potentially long linking stage is done twice though, which will make the compile/test cycle even worse. In case you're wondering my ultimate goal -- when compiling a library, undefined symbols in a local object file indicates a dependency wasn't specified that should have been in my build environment, whereas if a symbol is missing in a library that you're linking against that's not an error (-l flags are only given for immediate dependencies, not dependencies of dependencies, under this system). I need the report for the part where it lists "referenced in file" so I can see whether the symbol was referenced by a local object or a library being linked. The --allow-shlib-undefined option almost fixes this but it doesn't work when linking against static libraries. Preference to solutions that will work with both the GNU and Solaris linkers.
From the GNU ld 2.15 NEWS file: Improved linker's handling of unresolved symbols. The switch --unresolved-symbols= has been added to tell the linker when it should report them and the switch --warn-unresolved-symbols has been added to make reports be issued as warning messages rather than errors.
1,568,568
1,568,687
How to convert Euler angles to directional vector?
I have pitch, roll, and yaw angles. How would I convert these to a directional vector? It'd be especially cool if you can show me a quaternion and/or matrix representation of this!
Unfortunately there are different conventions on how to define these things (and roll, pitch, yaw are not quite the same as Euler angles), so you'll have to be careful. If we define pitch=0 as horizontal (z=0) and yaw as counter-clockwise from the x axis, then the direction vector will be x = cos(yaw)*cos(pitch) y = sin(yaw)*cos(pitch) z = sin(pitch) Note that I haven't used roll; this is direction unit vector, it doesn't specify attitude. It's easy enough to write a rotation matrix that will carry things into the frame of the flying object (if you want to know, say, where the left wing-tip is pointing), but it's really a good idea to specify the conventions first. Can you tell us more about the problem? EDIT: (I've been meaning to get back to this question for two and a half years.) For the full rotation matrix, if we use the convention above and we want the vector to yaw first, then pitch, then roll, in order to get the final coordinates in the world coordinate frame we must apply the rotation matrices in the reverse order. First roll: | 1 0 0 | | 0 cos(roll) -sin(roll) | | 0 sin(roll) cos(roll) | then pitch: | cos(pitch) 0 -sin(pitch) | | 0 1 0 | | sin(pitch) 0 cos(pitch) | then yaw: | cos(yaw) -sin(yaw) 0 | | sin(yaw) cos(yaw) 0 | | 0 0 1 | Combine them, and the total rotation matrix is: | cos(yaw)cos(pitch) -cos(yaw)sin(pitch)sin(roll)-sin(yaw)cos(roll) -cos(yaw)sin(pitch)cos(roll)+sin(yaw)sin(roll)| | sin(yaw)cos(pitch) -sin(yaw)sin(pitch)sin(roll)+cos(yaw)cos(roll) -sin(yaw)sin(pitch)cos(roll)-cos(yaw)sin(roll)| | sin(pitch) cos(pitch)sin(roll) cos(pitch)sin(roll)| So for a unit vector that starts at the x axis, the final coordinates will be: x = cos(yaw)cos(pitch) y = sin(yaw)cos(pitch) z = sin(pitch) And for the unit vector that starts at the y axis (the left wing-tip), the final coordinates will be: x = -cos(yaw)sin(pitch)sin(roll)-sin(yaw)cos(roll) y = -sin(yaw)sin(pitch)sin(roll)+cos(yaw)cos(roll) z = cos(pitch)sin(roll)
1,568,659
1,568,758
What are some rules with included headers?
I keep running into problems the larger my program gets. For instance, I get the following error: In file included from WidgetText.h:8, from LCDText.h:17, from WidgetText.cpp:13: Generic.h:21: error: expected class-name before ',' token Here are those lines: #include "Generic.h" // WidgetText.h:8 #include "WidgetText.h" // LCDText.h:17 #include "LCDText.h" // WidgetText.cpp:13 class Generic: public virtual LCDText, public CFG, public virtual Evaluator { // Generic.h:21 Here are the contents of the various header files: //Generic.h #include "CFG.h" #include "Evaluator.h" #include "LCDText.h" #include "Widget.h" //WidgetText.h #include "Generic.h" #include "Property.h" #include "Widget.h" //LCDText.h class Generic; #include "LCDBase.h" #include "WidgetText.h" This isn't providing much; I know. I'm not sure what else to include. Each header defines a class named after its header, so LCDText.h has a class named LCDText. The one line declaring class 'Generic' in LCDText.h had to be placed there due to an earlier problem similar to this one. I'm assuming this current issue has a similar solution, but I've failed to find it thus far.
Part of the solution is to add some forward declarations to get rid of these compiler errors (just like you did with your class Generic line). Google will turn up lots of suggestions on how exactly to do this. Using forward declarations will let you eliminate the cyclic / circular #includes described in this answer. A forward declaration lets you include references to and pointers to the forward-declared class, and it lets you pass the forward-declared class as a parameter, but it does not let you derive from or include an instance member of the forward-declared class. So your Generic class needs a way to #include (and not just forward-declare) the header files for LCDText, CFG, and Evaluator. If it can't do that because LCDText, CFG, or Evaluator need to #include (and not just forward-declare) Generic, then you need to rearrange your hierarchy to fix this (for example, by making a member variable a pointer or reference to a class instead of making it an instance of a class). However, using multiple inheritance like this (and especially using the diamond inheritance implied by two virtual inheritances) is a definite code smell. It suggests that you should be designing your class hierarchy differently. For example, maybe you need to be favoring composition over inheritance. That would make cleaning up your forward declarations and cyclic dependencies a lot easier. Edit: You mentioned that you've been running into this problem more as your code base gets larger. I'm told that John Lakos's Large-Scale C++ Software Design is a good reference for managing issues such as header file dependencies in large projects, although it may be overkill for where your project is right now.