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,508,389
1,508,507
How to convert char* to PRUnichar *
I need to pass char* to XPCOM function but that function accepts PRUnichar *. How to convert from char* to PRUnichar * ?
Take a look at nsAutoString.
1,508,454
1,508,514
Is the use of vectors of pointers here unnecessary or worse, cause memory leaks?
I am relatively new to C++ programming, but am a C programmer of 10 years so am more comfortable with pointers to objects than I am with references to objects. I'm writing a Solitaire game - is this design unsafe? Is there a better way? Anyway, I have a class SolitaireGame: class SolitaireGame: { public: SolitaireGame( int numsuits = 1 ); private: Deck * _deck; vector<Card> _shoe; }; The Deck is defined thus: class Deck: { public: Deck::Deck( vector<Card>& shoe ); ~Deck(); int DealsLeft() const { return deals_left; } Card * PullCard(); private: int deals_left; int num_each_deal; deque<Card *> _cards; }; The Deck constructor, takes a reference to a vector of Card objects ( the shoe, normally 104 cards ) and pushes a pointer to each card onto it's own deque of pointers. Deck::Deck( vector<Card>& shoe ) { vector<Card>::iterator iter = shoe.begin(); while( iter != shoe.end() ) { _cards.push_front( &(*iter) ); iter++; } } } The shoe is created in the SolitaireGame constructor. Once this vector of dynamically created Card objects has been created - I then pass a reference to this vector to the constructor. SolitaireGame::SolitaireGame( int numsuits ):_numsuits(numsuits ) { Card * c; vector<Card> _shoe; for( int i = 0; i < NUM_CARDS_IN_SHOE; i++ ) { c = new Card(); _shoe.push_back( *c ); } _deck = new Deck( _shoe ); } My idea was that the shoe would be the container for the actual memory for the Card objects and the Deck and Columns just handle pointers to those Card objects.
Just taking this snippet of code, you leak dynamically created cards. Card * c; vector<Card> _shoe; for( int i = 0; i < NUM_CARDS_IN_SHOE; i++ ) { c = new Card(); _shoe.push_back( *c ); } _shoe.push_back( *c ) adds a copy of the Card object pointed to by c to the vector of Cards. You then fail to delete the original Card as created in the line before. Allocating a vector of NUM_CARDS_IN_SHOE Cards can much more simply be achieved like this: std::vector<Card> _shoe( NUM_CARDS_IN_SHOE ); Looking at your card structure, it looks like you have (or nearly have) strict ownership between objects so I don't think that you need to dynamically create your Cards. Note that your local variable _shoe is shadowing the class variable _shoe. This probably isn't what you want as the local _shoe which you pass to the Deck constructor will go out of scope at the end of the constructor. If you reorder you variables in SolitaireGame, you can probably do something like this: class SolitaireGame: { public: SolitaireGame( int numsuits = 1 ); private: vector<Card> _shoe; Deck _deck; }; SolitaireGame::SolitaireGame( int numsuits ) : _shoe(NUM_CARDS_IN_SHOE) , _deck(_shoe) { } I've changed _deck from being a pointer. I'm using the fact that member variables are constructed in the order declared in the class definition, so _shoe will be fully constructed before it is passed as a reference to the constructor for _deck. The advantage of this is that I have eliminated the need to dynamically allocate _deck. With no uses of new, I know that I can't have any missed calls to delete as nothing needs to be deallocated explicitly. You are right that you can store pointers to the Cards in _shoe in your _deck without any memory management issues, but note that you must not add or remove any of the Cards in the _shoe during the lifetime of the game otherwise you will invalidate all of the pointers in _deck.
1,508,658
1,508,749
Accessing the QTabBar instance
How can I get access to the QTabBar of a QTabWidget? The only solution I've found is to subclass QTabWidget and override the protected QTabWidget::getTabBar() as public. Is there any other way of doing this?
tabBar->findChild<QTabBar *>(QLatin1String("qt_tabwidget_tabbar"));
1,508,928
1,508,952
Friend class and all its descendants
suppose that I have a class A with several subclasses (B, C, and D). I need B C and D to access some protected members from a class E. Is it possible to make B, C and D friends of E in a single hit without having to list them all? I have tried with: class E { friend class A; ... }; But this doesn't work. Thank you
You can put protected accessor functions in A, and have A be a friend of E. That way, all derived classes of A can access the members of E via the accessor functions.
1,509,002
1,509,035
CWinAppEx undefined class
Hey, I created a dialog base application using the wizard in VS C++ 2008. Haven't added any code my self. When I compile I get a few errors saying that CWinAppEx is undefined. c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.h(19) : error C2504: 'CWinAppEx' : base class undefined c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(16) : error C2146: syntax error : missing ';' before identifier 'TheBaseClass' c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(16) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(16) : error C2065: 'TheBaseClass' : undeclared identifier c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(17) : error C2248: 'CWinApp::OnHelp' : cannot access protected member declared in class 'CWinApp' c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxwin.h(4953) : see declaration of 'CWinApp::OnHelp' c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxwin.h(4737) : see declaration of 'CWinApp' c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(18) : error C2653: 'TheBaseClass' : is not a class or namespace name c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(49) : error C2653: 'CWinAppEx' : is not a class or namespace name c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(60) : error C3861: 'SetRegistryKey': identifier not found c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.cpp(63) : error C2065: 'm_pMainWnd' : undeclared identifier IvrEngineDlg.cpp c:\documents and settings\hussain\my documents\visual studio 2008\projects\ivrengine\ivrengine\ivrengine.h(19) : error C2504: 'CWinAppEx' : base class undefined
CWinAppEx is available only if you have installed Visual Studio 2008 SP1, which I think you already have since you were able to generate with the wizard code that uses CWinAppEx. CWinAppEx is located in afxwinappex.h, maybe you don't have this include in the stdafx.h header.
1,509,059
1,509,082
C++ Laws? (similar to Law of Big Three)
I have been reading C++ and writing small programs in it for more than a year. Recently I came across Law of The Big Three. I never knew about this law. Accidentally, I found it here: Rule of Three. May I know any other such laws in C++?
You're probably looking for C++ "best practices", not "laws". This should help you searching on the net. Moreover, there's a book called "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu which is supposed to be good, but I haven't read it myself. You can order it, e.g., over at amazon.com.
1,509,277
1,510,143
Why does wide file-stream in C++ narrow written data by default?
Honestly, I just don't get the following design decision in C++ Standard library. When writing wide characters to a file, the wofstream converts wchar_t into char characters: #include <fstream> #include <string> int main() { using namespace std; wstring someString = L"Hello StackOverflow!"; wofstream file(L"Test.txt"); file << someString; // the output file will consist of ASCII characters! } I am aware that this has to do with the standard codecvt. There is codecvt for utf8 in Boost. Also, there is a codecvt for utf16 by Martin York here on SO. The question is why the standard codecvt converts wide-characters? why not write the characters as they are! Also, are we gonna get real unicode streams with C++0x or am I missing something here?
The model used by C++ for charsets is inherited from C, and so dates back to at least 1989. Two main points: IO is done in term of char. it is the job of the locale to determine how wide chars are serialized the default locale (named "C") is very minimal (I don't remember the constraints from the standard, here it is able to handle only 7-bit ASCII as narrow and wide character set). there is an environment determined locale named "" So to get anything, you have to set the locale. If I use the simple program #include <locale> #include <fstream> #include <ostream> #include <iostream> int main() { wchar_t c = 0x00FF; std::locale::global(std::locale("")); std::wofstream os("test.dat"); os << c << std::endl; if (!os) { std::cout << "Output failed\n"; } } which use the environment locale and output the wide character of code 0x00FF to a file. If I ask to use the "C" locale, I get $ env LC_ALL=C ./a.out Output failed the locale has been unable to handle the wide character and we get notified of the problem as the IO failed. If I run ask an UTF-8 locale, I get $ env LC_ALL=en_US.utf8 ./a.out $ od -t x1 test.dat 0000000 c3 bf 0a 0000003 (od -t x1 just dump the file represented in hex), exactly what I expect for an UTF-8 encoded file.
1,509,301
1,509,323
reference a filename in vi
Sometimes I run make directly from the vim command line. However, sometimes I would just like to build one file currently being edited: !g++ filename.cpp . Is there a shortcut to reference the file without having to type it..? Guys, I DO NOT want to use make at all. all I want to do is to build it from vi's command line, using g++/gcc
You can use % to reference the current file so: :!g++ %
1,509,855
1,509,886
how to move to the next enclosing brackets in VI
Are there any shortcuts to move to the next enclosing brackets. For ex: int func() { if(true) {//this point for(int i=0;i<10;i++) {//need to jump from here to //blah blah blah } } } I can move to the beginning of a function using [[ but not sure how to move to the next enclosing brackets. Thanks for any info...
Can't think of anything easier than /{ [{ will go to an unmatched one, but that isn't what you want.
1,510,346
1,546,191
how to upload file by POST in libcurl?
how to upload file by POST in libcurl?(c++)
Are you referring to RFC 1867 (i.e., what the browser sends when the user submits an HTML form containing an input field with type="file")? If that's the case, you may be interested in http://curl.haxx.se/libcurl/c/postit2.html
1,510,945
2,608,616
Modifying bundled properties from visitor
How should I modify the bundled properties of a vertex from inside a visitor? I would like to use the simple method of sub-scripting the graph, but the graph parameter passed into the visitor is const, so compiler disallows changes. I can store a reference to the graph in the visitor, but this seems weird. /** A visitor which identifies vertices as leafs or trees */ class bfs_vis_leaf_finder:public default_bfs_visitor { public: /** Constructor @param[in] total reference to int variable to store total number of leaves @param[in] g reference to graph ( used to modify bundled properties ) */ bfs_vis_leaf_finder( int& total, graph_t& g ) : myTotal( total ), myGraph( g ) { myTotal = 0; } /** Called when the search finds a new vertex If the vertex has no children, it is a leaf and the total leaf count is incremented */ template <typename Vertex, typename Graph> void discover_vertex( Vertex u, Graph& g) { if( out_edges( u, g ).first == out_edges( u, g ).second ) { myTotal++; //g[u].myLevel = s3d::cV::leaf; myGraph[u].myLevel = s3d::cV::leaf; } else { //g[u].myLevel = s3d::cV::tree; myGraph[u].myLevel = s3d::cV::tree; } } int& myTotal; graph_t& myGraph; };
Your solution is right. To decouple the graph type from the visitor you could pass only the interesting property map to the visitor constructor and access its elements using boost::get(property, u) = s3d::cV::leaf;. This way you can pass any type-compatible vertex property to the visitor (the visitor will be more general and not sensible to name changes in the graph type). The type for the property map will be a template type-name for the visitor class and will be something like: typedef property_map<graph_t, s3d_cv3_leaf_t your_vertex_info::*>::type your_property_map; See here for a complete dissertation about bundled properties. HTH
1,510,989
1,511,012
Can C++ be compiled into platform independent code? Why Not?
Is it possible to compile C++ program into some intermediate stage (similar to bytecode in java) where the output is platform independent and than later compile/link at runtime to run in native (platform dependent) code? If answer is no, why?
It is indeed possible, see for example LLVM.
1,511,029
1,583,334
Tokenize a string and include delimiters in C++
I'm tokening with the following, but unsure how to include the delimiters with it. void Tokenize(const string str, vector<string>& tokens, const string& delimiters) { int startpos = 0; int pos = str.find_first_of(delimiters, startpos); string strTemp; while (string::npos != pos || string::npos != startpos) { strTemp = str.substr(startpos, pos - startpos); tokens.push_back(strTemp.substr(0, strTemp.length())); startpos = str.find_first_not_of(delimiters, pos); pos = str.find_first_of(delimiters, startpos); } }
The C++ String Toolkit Library (StrTk) has the following solution: std::string str = "abc,123 xyz"; std::vector<std::string> token_list; strtk::split(";., ", str, strtk::range_to_type_back_inserter(token_list), strtk::include_delimiters); It should result with token_list have the following elements: Token0 = "abc," Token1 = "123 " Token2 = "xyz" More examples can be found Here
1,511,101
1,511,113
What is easiest way to create multithreaded applications with C/C++?
What is the easiest way to create multithreaded applications with C/C++?
unfortunately there is no easy way. Couple of options: pthread on linux, win32 api threads on windows or boost::thread library
1,511,129
1,512,608
boost::asio::ip::tcp::socket is connected?
I want to verify the connection status before performing read/write operations. Is there a way to make an isConnect() method? I saw this, but it seems "ugly". I have tested is_open() function as well, but it doesn't have the expected behavior.
TCP is meant to be robust in the face of a harsh network; even though TCP provides what looks like a persistent end-to-end connection, it's all just a lie, each packet is really just a unique, unreliable datagram. The connections are really just virtual conduits created with a little state tracked at each end of the connection (Source and destination ports and addresses, and local socket). The network stack uses this state to know which process to give each incoming packet to and what state to put in the header of each outgoing packet. Because of the underlying — inherently connectionless and unreliable — nature of the network, the stack will only report a severed connection when the remote end sends a FIN packet to close the connection, or if it doesn't receive an ACK response to a sent packet (after a timeout and a couple retries). Because of the asynchronous nature of asio, the easiest way to be notified of a graceful disconnection is to have an outstanding async_read which will return error::eof immediately when the connection is closed. But this alone still leaves the possibility of other issues like half-open connections and network issues going undetected. The most effectively way to work around unexpected connection interruption is to use some sort of keep-alive or ping. This occasional attempt to transfer data over the connection will allow expedient detection of an unintentionally severed connection. The TCP protocol actually has a built-in keep-alive mechanism which can be configured in asio using asio::tcp::socket::keep_alive. The nice thing about TCP keep-alive is that it's transparent to the user-mode application, and only the peers interested in keep-alive need configure it. The downside is that you need OS level access/knowledge to configure the timeout parameters, they're unfortunately not exposed via a simple socket option and usually have default timeout values that are quite large (7200 seconds on Linux). Probably the most common method of keep-alive is to implement it at the application layer, where the application has a special noop or ping message and does nothing but respond when tickled. This method gives you the most flexibility in implementing a keep-alive strategy.
1,511,323
1,512,153
How to stop MFC from disabling my controls if I don't declare a message map entry for it's corresponding command?
I have the following problem: MFC is disabling my toolbar (a CToolbar) controls if I don't have a message map entry for it's corresponding message (let's say ID_MYBUTTON1). Is there a way around this? I had the same problems with the menu but I found that you could disable the auto disabling by setting CFrameWnd::m_bAutoMenuEnable to false but I cannot find a similar member for CToolbar. I guess I could add handlers redirecting to an empty function but it would be nice if I could just stop this behavior without using "tricks". Thanks
Well like I said in reply to zdan's answer I found a way. Just override the OnUpdateCmdUI function in CToolBar like this class MyToolBar : public CToolBar { public: virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { return CToolBar::OnUpdateCmdUI(pTarget, FALSE);} } the bDisableIfNoHndler flag is the one responsible for telling the toolbar to disable buttons if no handlers is found so I just force it to FALSE. Though now I'm having another problem. The toolbar seem fines but it do not send the commands when I press a button. I'm not sure why because if I access the same commands from the menu it works fine. I'll try to see if this is related. Thanks for your helps. Update: Found my problem. Basically the problem was that my handlers to my commands were in MyFrame::PreTranslateMessage (after doing like suggested in this question's answer : How to redirect MFC messages to another object?) but the commands were not sent through this function (though when accessed from the menu they did). They were sent through MyFrame::OnCommand though so I just changed the code from PreTranslateMessage to OnCommand and now everything works fine. I don't know MFC enough to know why this was the case but now everything seems to works so thanks for the help everyone.
1,511,532
1,511,547
Variable length template arguments list?
I remember seing something like this being done: template <ListOfTypenames> class X : public ListOfTypenames {}; that is, X inherits from a variable length list of typenames passed as the template arguments. This code is hypothetical, of course. I can't find any reference for this, though. Is it possible? Is it C++0x?
You can do it in current C++. You give the template a "large enough" number of parameters, and you give them defaults: class nothing1 {}; class nothing2 {}; class nothing3 {}; template <class T1 = nothing1, class T2 = nothing2, class T3 = nothing3> class X : public T1, public T2, public T3 {}; Or you can get more sophisticated and use recursion. First you forward-declare the template: class nothing {}; template <class T1 = nothing, class T2 = nothing, class T3 = nothing> class X; Then you specialise for the case where all the parameters are default: template <> class X<nothing, nothing, nothing> {}; Then you properly define the general template (which previously you've only forward-declared): template <class T1, class T2, class T3> class X : public T1, public X<T2, T3> Notice how in the base class, you inherit X but you miss the first parameter. So they all slide along one place. Eventually they will all be defaults, and the specialization will kick in, which doesn't inherit anything, thus terminating the recursion. Update: just had a strange feeling I'd posted something like this before, and guess what...
1,511,636
2,992,155
How to use hudson when building for multiple platforms
Right now we are building a number of C++ apps for Win32 platform. We will be soon porting to Linux and then maybe more (32 and 64 bits for both). What is the standard practice , do you use multiple hudson servers each on their own platform to do a build, or does the hudson service create VMs and do builds? It is not clear to me the best practical way to do this. Ideally I just want one box with a bunch of VMs running hudson, and then it kicks off builds as needed. Is there a resource someone can point me to for this?
We use Hudson to manage C/C++ (GNU C, GNU C++, Watcom C) builds for multiple OSs. For us, software is built for Linux, Linux x64, QNX 4, and QNX6. The way we have it set up is: 1 x VM for the Hudson server, running Windows 4 x VMs, one for each slave type, so I have 4 Hudson slaves - 1 each for QNX4, QNX6 and Linux 32 and Linux 64. All of them are running on the same server, just as different VMs, and we have faced no problems. We build about a 100 projects, divided almost equally between the 4 system types. You should not require any additional hardware. There is a Hudson plugin that works with VMWare VMs, to start them up and shut them down as required. I hope that helps.
1,511,797
1,511,885
convert string to argv in c++
I have an std::string containing a command to be executed with execv, what is the best "C++" way to convert it to the "char *argv[]" that is required by the second parameter of execv()? To clarify: std::string cmd = "mycommand arg1 arg2"; char *cmd_argv[]; StrToArgv(cmd, cmd_argv); // how do I write this function? execv(cmd_argv[0], cmd_argv);
std::vector<char *> args; std::istringstream iss(cmd); std::string token; while(iss >> token) { char *arg = new char[token.size() + 1]; copy(token.begin(), token.end(), arg); arg[token.size()] = '\0'; args.push_back(arg); } args.push_back(0); // now exec with &args[0], and then: for(size_t i = 0; i < args.size(); i++) delete[] args[i]; Of course, this won't work with commans that use quoting like rm "a file.mp3". You can consider the POSIX function wordexp which cares about that and much more.
1,511,935
1,512,164
Differences between template specialization and overloading for functions?
So, I know that there is a difference between these two tidbits of code: template <typename T> T inc(const T& t) { return t + 1; } template <> int inc(const int& t) { return t + 1; } and template <typename T> T inc(const T& t) { return t + 1; } int inc(const int& t) { return t + 1; } I am confused as to what the functional differences between these two are. Can someone show some situations where these snippits act differently from each other?
I can only think of a few differences - here are some examples that don't necessarily cause harm (i think). I'm omitting definitions to keep it terse template <typename T> T inc(const T& t); namespace G { using ::inc; } template <> int inc(const int& t); namespace G { void f() { G::inc(10); } } // uses explicit specialization // --- against --- template <typename T> T inc(const T& t); namespace G { using ::inc; } int inc(const int& t); namespace G { void f() { G::inc(10); } } // uses template That is because specializations are not found by name lookup, but by argument matching, so a using declaration will automatically consider a later introduced specialization. Then, you of course cannot partially specialize function templates. Overloading however accomplishes something very similar by partial ordering (using different types now, to make my point) template <typename T> void f(T t); // called for non-pointers template <typename T> void f(T *t); // called for pointers. int a; void e() { f(a); // calls the non-pointer version f(&a); // calls the pointer version } That wouldn't be possible with function template explicit specialization. Another example is when references are involved, which causes template argument deduction to look for an exact match of the types involved (modulo base/derived class relationships and constness): template<typename T> void f(T const &); template<> void f(int * const &); template<typename T> void g(T const &); void g(int * const &); int a[5]; void e() { // calls the primary template, not the explicit specialization // because `T` is `int[5]`, not `int *` f(a); // calls the function, not the template, because the function is an // exact match too (pointer conversion isn't costly enough), and it's // preferred. g(a); } I recommend you to always use overloading, because it's richer (allows something like partial specialization would allow), and in addition you can place function in whatever namespace you want (although then it's not strictly overloading anymore). For example, instead of having to specialize std::swap in the std:: namespace, you can place your swap overload in your own namespace and make it callable by ADL. Whatever you do, never mix specialization and overloading, it will be a hell of a mess like this article points out. The Standard has a lovely paragraph about it The placement of explicit specialization declarations for function templates, class templates, member functions of class templates, static data members of class templates, member classes of class templates, member class templates of class templates, member function templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, member function templates of member classes of class templates, etc., and the placement of partial specialization declarations of class templates, member class templates of non-template classes, member class templates of class templates, etc., can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below. When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.
1,511,988
1,512,075
convert a pointer to a reverse vector iterator in STL
I have sort(arr, arr+n, pred); How do I sort in reverse order?
There also seems to be a possibility to use reverse iterators ... except using the reversed predicate might be easier, except perhaps when the type doesn't implement operator> :) #include <iostream> #include <algorithm> #include <iterator> int main() { int arr[4] = { 3, 2, 5, 4 }; std::sort(std::reverse_iterator<int*>(arr + 4), std::reverse_iterator<int*>(arr)); }
1,512,174
1,512,791
Is it possible to define a variable in expression in C++?
I have this insane homework where I have to create an expression to validate date with respect to Julian and Gregorian calendar and many other things ... The problem is that it must be all in one expression, so I can't use any ; Are there any options of defining variable in expression? Something like d < 31 && (bool leapyear = y % 4 == 0) || (leapyear ? d % 2 : 3) .... where I could define and initialize one or more variables and use them in that one expression without using any ;? Edit: It is explicitly said, that it must be a one-line expression. No functions .. The way I'm doing it right now is writing macros and expanding them, so I end up with stuff like this #define isJulian(d, m, y) (y < 1751 || (y == 1752 && (m < 9) || (m == 9 && d <= 2))) #define isJulianLoopYear(y) (y % 4 == 0) #define isGregorian(d, m, y) (y > 1573 || (y == 1752 && (m > 9) || (m == 9 && d > 13))) #define isGregorianLoopYear(y) ((y % 4 == 0) || (y % 400 = 0)) // etc etc .... looks like this is the only suitable way to solve the problem edit: Here is original question Suppose we have variables d m and y containing day, month and year. Task is to write one single expression which decides, if date is valid or not. Value should be true (non-zero value) if date is valid and false (zero) if date is not valid. This is an example of expression (correct expression would look something like this): d + 4 == y ^ 85 ? ~m : d * (y-2) These are examples of wrong answers (not expressions): if ( log ( d ) == 1752 ) m = 1; or: for ( i = 0; i < 32; i ++ ) m = m / 2; Submit only file containing only one single expression without ; at the end. Don't submit commands or whole program. Until 2.9.1752 was Julian calendar, after that date is Gregorian calendar In Julian calendar is every year dividable by 4 a leap year. In Gregorian calendar is leap year ever year, that is dividible by 4, but is not dividible by 100. Years that are dividable by 400 are another exception and are leap years. 1800, 1801, 1802, 1803, 1805, 1806, ....,1899, 1900, 1901, ... ,2100, ..., 2200 are not loop years. 1896, 1904, 1908, ..., 1996, 2000, 2004, ..., 2396,..., 2396, 2400 are loop years In september 1752 is another exception, when 2.9.1752 was followed by 14.9.1752, so dates 3.9.1752, 4.9.1752, ..., 13.9.1752 are not valid.
((m >0)&&(m<13)&&(d>0)&&(d<32)&&(y!=0)&&(((d==31)&& ((m==1)||(m==3)||(m==5)||(m==7)||(m==8)||(m==10)||(m==12))) ||((d<31)&&((m!=2)||(d<29)))||((d==29)&&(m==2)&&((y<=1752)?((y%4)==0): ((((y%4)==0)&&((y%100)!=0)) ||((y%400)==0)))))&&(((y==1752)&&(m==9))?((d<3)||(d>13)):true))
1,512,378
1,512,385
Visual Studio 2008 IDE - Static Linking a C Dll Library
I am experiencing Frustration ^ Frustraion with this %&$^& VS IDE. I am using Visual C++ 2008 3.5 SP1 (but I also have the pro edition if that is needed and I dont want to use loadlibrary()) I have a test Dll created in another language (basic not C in fact) that contains a CDECL function that adds an 'int' to a 'double'. I would really like to add an int to a float using STDCALL, but if can get the former to work first that would be a major acheivement. I have read extensively and tried: http://support.microsoft.com/kb/313981 http://www.codeproject.com/KB/DLL/loadingdll.aspx Linking to a static lib that links to a static lib statically and dynamically linking DLLs generated with different versions of Visual Studio I wrote a nice header file for the AddShow.dll called AddShow.h DLLAPI int __cdecl AddTwoNum(int n, double f); Then I used this nifty tool to create the .lib file: http://www.binary-soft.com/dll2lib/dll2lib.htm Now what? I tried right click and 'Add' then 'Class" then 'Componant Class' then specifying the path and name of the dll, but I get 8 miles of bloat and the entire windows toolbox and a new AddShow.cpp file. My C++ code is really simply: extern int __cdecl AddTwoNum(int n, double f); int main() { int n, RetVal; double d; n = 33; d = 66.6; RetVal = AddTwoNum(n, d); cout << "RetVal=" << RetVal; return 0; } How do I just get the IDE to link the .lib file? ADDED: after linking (.lib file is in the debug file) I get the following error: Compiling... main.cpp Linking... main.obj : error LNK2019: unresolved external symbol "int __cdecl AddTwoNum(int,double)" (?AddTwoNum@@YAHHN@Z) referenced in function _main C:\C++\FirstDll\Debug\FirstDll.exe : fatal error LNK1120: 1 unresolved externals Build log was saved at "file://c:\C++\FirstDll\FirstDll\Debug\BuildLog.htm" FirstDll - 2 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
You can go to: Project Properties -> Linker -> Input Then add your .lib to the "Additional Dependencies". Additionally, you can put #pragma comment(lib, "<your .lib>") in your .cpp file.
1,512,476
1,512,485
What are these GCC/G++ parameters?
I've been using the UVa Online Judge to solve some programming challenges, and, when submitting my solutions, I'm told the judge will compile my code using the following parameters to GCC/G++ that I don't know: -lm -lcrypt -pipe -DONLINE_JUDGE. What do they do? Thank you very much in advance!
"-lm -lcrypt" specifies to link with the math and cryptography libraries - useful if you're going to use the functions defined in math.h and crypt.h. "-pipe" just means it won't create intermediate files but will use pipes instead. "-DONLINE_JUDGE" defines a macro called "ONLINE_JUDGE", just as if you'd put a "#define" in your code. I guess that's so you can put something specific to the judging in your code in an "#ifdef"/"#endif" block.
1,512,520
1,512,577
Decent shared_ptr implementation that does not require a massive library?
I am taking a C++ programming class right now on GIS Programming. I am really starting to get alot of headaches from dealing with proper memory management. Considering at any time there is often 8-10 classes each holding a pointer to a 3D matrix or something else very large. Now our class already raised the issue of the prof allowing us to use Boost, or atleast the C++ Feature Pack for 2008(for TR1). He refused but said if we wanted to we can find add a few third party cpp/hpp files. I already tried looking at getting shared_ptr out of boost but that is more of a headache than its worth. So is there any sort of free shared_ptr implementation out there?
Use boost's bcp tool. It will let you extract certain functionality from the boost libraries. bcp shared_ptr /boost_shared_ptr will extract shared_ptr and it's dependencies to that directory.
1,512,555
1,512,566
How can I display +/- icons on my tree view?
I want to make a tree view where items show a "+" icon when closed and a "-" icon when open. Just like the Windows XP explorer. However, I can't find out how to get the icons. Do I get them from the system or do I need to provide my own?
The tree-view control will display the icons if you set the TVS_HASBUTTONS style.
1,512,653
1,512,657
What does it mean when I "cannot convert X** to X*" in a "new" assignment?
In running Ubuntu and the g++ compiler I keep getting the same error from this code. myClass *arr; arr = new myClass*[myClassSize]; // line 24 for(int a = 0;a<myClassSize;a++) arr[a] = new myClass; Here is the error: cannot convert 'myClass **' to 'myClass *' in assignment The problem was on line 24.
You need an extra * in the declaration of arr: myClass** arr; You seem to be trying to make an array of pointers, but type* is just a pointer to type / array of type.
1,512,972
1,512,991
What is the optimization level (g++) you use while comparing two different algorithms written in C++?
I have two algorithms written in C++. As far as I know, it is conventional to compile with -O0 -NDEBUG (g++) while comparing the performance of two algorithms(asymptotically they are same). But I think the optimization level is unfair to one of them, because it uses STL in every case. The program which uses plain array outperforms the STL-heavy algorithm 5 times faster while compiled with -O0 options. But the performance difference is not much different when I compile them with -O2 -NDEBUG. Is there any way to get the best out of STL (I am getting heavy performance hit in the vector [] operator) in optimization level -O0? What optimization level (and possibly variables like -NDEBUG) do you use while comparing two algorithms? It will be also great help if someone can give some idea about the trend in academic research about comparing the performance of algorithms written in C++? Ok, To isolate the problem of optimization level, I am using one algorithm but two different implementation now. I have changed one of the functions with raw pointers(int and boolean) to std::vector and std::vector... With -O0 -NDEBUG the performances are 5.46s(raw pointer) and 11.1s(std::vector). And with -O2 -NDEBUG , the performances are 2.02s(raw pointer) and 2.21s(std::vector). Same algorithm, one implementation is using 4/5 dynamic arrays of int and boolean. And the other one is using using std::vector and std::vector instead. They are same in every other case You can see that in -O0 std::vector is outperformed with twice faster pointers. While in -O2 they are almost the same. But I am really confused, because in academic fields, when they publish the results of algorithms in running time, they compile the programs with -O0. Is there some compiler options I am missing?
It depends on what you want to optimize for. Speed I suggest using -O2 -NDEBUG -ftree-vectorize, and if your code is designed to specifically run on x86 or x86_64, add -msse2. This will give you a broad idea on how it will perform with GIMPLE. Size I believe you should use -Os -fno-rtti -fno-exceptions -fomit-frame-pointer. This will minimize the size of the executable to a degree (assuming C++). In both cases, algorithm's speed is not compiler dependent, but a compiler can drastically change the way the code behaves if it can "prove" it can. GCC detects 'common' code such as hand-coded min() and max() and turns them into one SSE instruction (on x86/x86_64 and when -msse is set) or using cmov when i686 is available (SSE has higher priority). GCC will also take liberty in reordering loops, unrolling and inlining functions if it wants to, and even remove useless code. As for your latest edit: You can see that in -O0 std::vector is outperformed with twice faster pointers. While in -O2 they are almost the same. That's because std::vector still has code that throws exceptions and may use rtti. Try comparing with -O2 -NDEBUG -ftree-vectorize -fno-rtti -fno-exceptions -fomit-frame-pointer, and you'll see that std::vector will be slightly better than your code. GCC knows what 'built-in' types are and how to exploit them in real world use and will gladly do so - just like it knows what memset() and memcpy() does and how to optimize accordingly when copy size is known.
1,512,990
1,513,010
What is the difference between int x=1 and int x(1) in C++?
Possible Duplicate: Is there a difference in C++ between copy initialization and assignment initialization? I am new to C++, I seldom see people using this syntax to declare and initialize a variable: int x(1); I tried, the compiler did not complain and the output is the same as int x=1, are they actually the same thing? Many thanks to you all.
Yes, for built in types int x = 1; and int x(1); are the same. When constructing objects of class type then the two different initialization syntaxes are subtly different. Obj x(y); This is direct initialization and instructs the compiler to search for an unambiguous constructor that takes y, or something that y can be implicitly converted to, and uses this constructor to initialize x. Obj x = y; This is copy initialization and instructs the compiler to create a temporary Obj by converting y and uses Obj's copy constructor to initalize x. Copy initalization is equivalent to direct initialization when the type of y is the same as the type of x. For copy initalization, because the temporary used is the result of an implicit conversion, constructors marked explicit are not considered. The copy constructor for the constructed type must be accessible but the copy itself may be eliminated by the compiler as an optmization.
1,513,040
1,513,271
Notification when a thread is destroyed
Is there a way to get a notification that a thread no longer runs (has returned) in your application? I know this is possible in kernel mode (using PsSetCreateThreadNotifyRoutine), but is there a way to know this from user mode, using only Win32 API ? The problem is that I can't control the code in the thread, because my module is part of a library. Making a driver to monitor the system would not be too hard, but it's annoying for the users to install a driver even for a basic application that uses my library. My code uses TLS storage, and under Linux/Unix pthread_key_create can take a pointer to a function that is called when the thread is destroyed. But TlsAlloc (Windows) has nothing like this... Thanks in advance!
Depends on what kind of libraray you have. For a DLL could handle the thread termination in your DllMain (DLL_THREAD_DETACH). The MSDN states that this is the best place to deal with TLS Resources. Keep in mind that this callback is only calld for a thread exiting cleanly (not by e.g TerminateThread()).
1,513,092
1,518,599
Sending IOCTL from IRQL=DISPATCH_LEVEL (KbFilter/KMDF)
I am using the KbFilter example in the WDK, trying to send an IOCTL in a function that is called by KbFilter_ServiceCallback and therefore is executed at DISPATCH_LEVEL. The function just has to send an IOCTL and return, am not waiting for an output buffer to be filled so it can be asynchronous, fire and forget. I am currently using the WDF functions WdfIoTargetFormatRequestForIoctl and WdfRequestSend to try and send at DISPATCH_LEVEL and getting nothing. The call to WdfRequestSend is succeeding but the IOCTL doesn't appear to be received. Using either of WdfIoTargetSendIoctlSynchronously or the WDM pattern IoBuildDeviceIoControlRequest() and IoCallDriver() requires PASSIVE_LEVEL and the only way I know to call these at PASSIVE_LEVEL is to create a separate thread that runs at PASSIVE_LEVEL and pass it instructions via a buffer or a queue, synchronized with a spinlock and semaphore. Can someone tell me if there is an easier way to pass IOCTLs to the drivers below my filter, or is the thread/queue approach the normal pattern when you need to do things at a higher IRQL? Under what circumstances can I use KeRaiseIrql and is this what I should use? Thanks.
Use IoAllocateIrp and IoCallDriver. They can be run at IRQL <= DISPATCH_LEVEL. You cannot lower your IRQL (unless it is you who raised it). KeRaiseIrql is used only to raise IRQL. A call to KeRaiseIrql is valid if the caller specifies NewIrql >= CurrentIrql. Be careful: Is your IOCTL expected at DISPATCH_LEVEL? Here is a code snippet: PIRP Irp = IoAllocateIrp(DeviceObject->StackSize, FALSE); Irp->Tail.Overlay.Thread = PsGetCurrentThread(); Irp->RequestorMode = KernelMode; Irp->IoStatus.Status = STATUS_NOT_SUPPORTED; Irp->IoStatus.Information = 0; PIO_STACK_LOCATION stack = IoGetNextIrpStackLocation(Irp); stack->MajorFunction = IRP_MJ_DEVICE_CONTROL; stack->Parameters.DeviceIoControl.IoControlCode = ...
1,513,214
1,525,596
Using GTK+ in Visual C++
I want to use GTK for user interface for C++ project. I do not know how to set development environment for it. I downloaded all-in-one bundle of gtk from http://www.gtk.org/download-windows.html How to use it with visual c++ 2008 ?
There are some old instructions here and here. You will probably have to adjust them for your needs. GTK also has some email lists you could join to discuss this. The best lists for this particular question are gtk-app-devel-list@gnome.org or gtk-list@gnome.org. There's also an irc channel, #gtk+ on irc.gnome.org. My experience there is you get either quick answers or no answers at all. If you can, you might try switching from Visual C++ to mingw, which is a Unix/Linux like build system for Windows. Very few GTK developers use it on Windows, and almost all of those people use mingw.
1,513,266
1,513,296
Legacy-C C++ incorporation
I'm currently working on a performance critical application which incorporates legacy c code (a SPICE variant). The problem is as follows: The creators of the legacy c code apparently believed that the use of argument passing is one of the great evils of the modern age. Thus about 90% of all the variables were declared globally. The legacy code has to be called repeatedly for simulation purposes and it would be seam that using threads for concurrent calls to this code section would be beneficial for the overall execution time. My idea was to encapsulate the legacy c code (which I already modified slightly for g++ compilation) so that multiple objects for the legacy code can be created removing the necessity of to many mutex locks. Obviously the global variables will thus be encapsulated as member variables. This brought another problem to the table. The legacy coders also did not believe in the initialization of global variables; probably since C tend to init global variables to 0. C++ member variables does not seam to get the same treatment though. A few variables has to be initialized to 0 for the correct operation of the legacy c code. But finding these variables have proven to be quite difficult due to the vast amount of global variables used. Please keep in mind that time does not permit me to modify the legacy c code to any major degree. My questions are as follows: Am I correct in the assumption that the encapsulation of the C code would be faster than the use of about 90 mutex locks? Is there an easy way of finding uninitialized member variable use? (As I understand gcc can only do this for automatic variables). So that I can init only the critical variables? If not Question 2 ... is there a fast and clean way to initialize all the member variables without using the normal constructor init method? Or (a long shot) is there a fast way of following program flow so that I might incorporate the argument passing myself? Any help will be vastly appreciated. N.B.
Yes. If you can put the state into objects to which you pass pointers around, it will be faster than locking, assuming you actually do use threads. No, it's not easy to find out unitialized member variables. Essentially, that would require to perform whole-code analysis, which it typically can't do (due to the existence of libraries) If you put all data in an old-style struct (i.e. no methods, no access declarations), you are allowed to memset() the entire struct to zero. This will cause initialization in the same way as global variables get initialized (which C does guarantee to initialize - to zero). If, by fast, you mean "automatic", then the answer is probably "no".
1,513,377
1,520,927
debugging 64 bit dumps in visual studio
Is there any way to use visual studio to debug a dump of a 32 bit app that was produced on a 64 bit computer. I have got WinDbg working but the output is so jumbled i cant work out whats going on. Visual Studio 2008
If you are new to debugging with WindDbg get yourself a copy of John Robbins: Debugging Microsoft .NET 2.0 Applications It is well worth the investment and has a great introductory section on debugging with WinDbg.
1,513,623
1,514,017
How to restrict proccess to create new processes?
How to restrict proccess to create new processes?
You could assign the process to a job object. Use SetInformationJobObject with the JOB_OBJECT_LIMIT_ACTIVE_PROCESS flag to limit the number of processes in that job object to one. Do NOT set the JOB_OBJECT_LIMIT_BREAKAWAY_OK (which would allow the process to create processes that were not part of the job object). The process could still work around that, such as by starting a new process via the task scheduler or WMI. If you're trying to do something like create a sandbox to run code you really don't trust, this won't adequate. If you have a program that you trust, but just want to place a few limits on what it does, this should be more than adequate. To put that slightly differently, this is equivalent to locking your car. Somebody can break in (or out, in this case), but at least they have to do a bit more than just walk in unhindered.
1,513,772
1,514,201
Resources on creating a GUI Layout Manager?
I have been working on a simple GUI and have hit a roadblock. I haven't found any examples or even readable source on how to create a GUI layout manager. I was wondering if anyone knew of some resources on creating one, or some source code that isn't cryptic like Qt's layout engine.
It depends on what you mean by "layout manager", and I'm not familiar with Qt, so that doesn't give me much of a clue. If you mean things like resizable window handling, though, I think the relevant term is "constraint solver". I've never looked into it that much, but I believe GUI constraint solvers are based on linear programming - the Simplex algorithm and all that. It might be possible to do something with Gaussian Elimination, but I'm far from confident about that. Based on a quick search for "gui layout linear programming", you might find this paper from CiteSeerX interesting - there's a PDF download. If you don't like cryptic, well, at a glance at least it's not exactly math heavy, but I suspect it's not light reading either. I guess I'll find out shortly, as you've got me interested.
1,513,910
1,717,531
Optimized Project Structure in Eclipse CDT
I'm in a c++ project on linux in the starting stages. (team contains 3-5 developer, IDE is Eclipse CDT 6) And i'm wondering your ideas about what should be the project structure about the following subjects: Dependency management, how would you reference different sub-project directories in the same project Building system, handwrite makefile or Eclipse automake? (Eclipse generates makefiles for per project. and i want a general makefile for all the subprojects) For A Test framework, would i prefer precompiled library or holding the source of framework on the project, then building with the overall building process? Sample sub-projects /Project.Model.A /Project.Model.B /Project.Model.A.Tests /Project.Model.B.Tests /Project.Views etc... And i'm looking for an open source project similar to this structure... best regards
Poco framework is suitable
1,513,920
1,513,961
Scripting language for C/C++?
Is there a scripting language for C++ (like perl) which can be used for rapid development and use some tool which can convert into C/C++ program to get higher performance for deployment? EDIT: Based on some commented, let me clarify the question. I should be able to convert script into C/C++ program or binary without modifying my script.
With a C/C++ interpreter you can use C/C++ as a scripting language. Ch: http://www.softintegration.com/ Commmercial C/C++ interpreter with a free Standard Edition. Has support for various popular libraries and windowing toolkits. CINT: http://root.cern.ch/drupal/content/cint Actively developed open-source (MIT license) C/C++ interpreter. Developed as part of the ROOT environment at the CERN. Used by many physicist. ccons: https://github.com/asvitkine/ccons An interactive C console which employs LLVM and its new C frontend (clang). Under active development UnderC: http://home.mweb.co.za/sd/sdonovan/underc.html An open-source (LGPL) C++ interpreter. Seems to be a bit dated (2002). Note: So far, I have tried only Ch and CINT. I have added ccons and UnderC to make the list more complete.
1,514,118
1,514,134
Disable automatic DLL loading in C++
My scenario is as follows: my application depends on a certain DLL (I use it's lib during linkage). However, when my application executes, I want to explicitly load that DLL using LoadLibrary. However, by default, when the code reaches a scope where that DLL is needed, the environment automatically look it up, and then loads it. I want to disable this behavior, and for all I care, if the application reached a point where it wants to execute code that belongs to that DLL, I prefer that it will crash instead of loading it automatically (So the DLL will be loaded only because I explicitly called LoadLibrary). In the meanwhile, I'm using the delay-load ability (so the load trigger will occur only when the DLL actually needs to be loaded). However, I would prefer that the application will just crash if the DLL wasn't loaded yet. Perhaps anyonehere is familiar with a way to achieve this?
If you want to use LoadLibrary, then don't link application with the import library. PE format doesn't support unresolved externals, so you either use headers and dllimport, or LoadLibrary, GetProcAddress and pointers to functions.
1,514,241
1,514,263
RegQueryValueEx - What code add to this function to show ERROR_SUCCESS
What code add to this function to work good? (ERROR_SUCCESS) I have code, that check value in registry. In function RegQueryValueEx is bug. When oldValue is few letters longer than newValue, function shows ERROR_MORE_DATA, but I want want ERROR_SUCCESS What code add to this function to do this? void function(string newValue, string key, string name) { // string key - key in registry, ie Myapp\\Options // string name - name in registry // string newValue - data in REG_SZ string oldValue; DWORD keytype = REG_SZ; HKEY keyHandle; DWORD size = sizeof(string); if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(),0L,KEY_ALL_ACCESS,&keyHandle) == ERROR_SUCCESS) { LONG isgood = RegQueryValueEx(keyHandle, name.c_str(), 0, &keytype, (LPBYTE)&oldValue, &size); if(isgood == ERROR_MORE_DATA) { cout << "Error more data\n"; } if(isgood == ERROR_SUCCESS) { cout << "Old data is " << oldValue.c_str() << endl; cout << "New data is " << newValue.c_str() << endl; if(strcmp(newValue.c_str(), oldValue.c_str()) != 0) // compare 2 strings, if { cout << "String 1 and string 2 are different"; } else { cout << "String 1 and string 2 are the same"; } } if(isgood == ERROR_FILE_NOT_FOUND) { cout << "Name in registry not found!"; } } }
ERROR_MORE_DATA means that you need to pass in a larger string buffer. The typical pattern you'll need to use is to call once to get the size, then allocate a properly-sized buffer, then call again. Or, alternatively, you can guess at a size, pass in that-sized buffer, and increase size if you get ERROR_MORE_DATA back. BTW, you are also computing size incorrectly. And you're not closing the registry key. And you're not prepared to support being compiled under unicode or non-unicode modes. Here's some revised code which addresses these issues. #include <string> #include <vector> #include <iostream> #include <windows.h> using namespace std; namespace std { #ifdef _UNICODE #define tcout wcout #define tcin wcin typedef wstring tstring; #else #define tcout cout #define tcin cin typedef string tstring; #endif }; void function(tstring newValue, tstring key, tstring name) { // string key - key in registry, ie Myapp\\Options // string name - name in registry // string newValue - data in REG_SZ HKEY keyHandle; if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(),0L,KEY_ALL_ACCESS,&keyHandle) == ERROR_SUCCESS) { DWORD size = 500; // initial size vector<TCHAR> buf(size); tstring oldValue; DWORD keytype = REG_SZ; LONG isgood = RegQueryValueEx(keyHandle, name.c_str(), 0, &keytype, (LPBYTE) &buf[0], &size); if(isgood == ERROR_SUCCESS) { oldValue.assign (&buf[0], size); } else if(isgood == ERROR_MORE_DATA) { buf.reserve (size); // expand to however large we need isgood = RegQueryValueEx(keyHandle, name.c_str(), 0, &keytype, (LPBYTE)&buf[0], &size); if(isgood == ERROR_SUCCESS) oldValue.assign (&buf[0], size); } RegCloseKey (keyHandle); // remember to close this! if(isgood == ERROR_SUCCESS) { tcout << _T("Old data is ") << oldValue << endl; tcout << _T("New data is ") << newValue << endl; if(newValue.compare(oldValue) != 0) // compare 2 strings, if { tcout << _T("String 1 and string 2 are different"); } else { tcout << _T("String 1 and string 2 are the same"); } } if(isgood == ERROR_FILE_NOT_FOUND) { tcout << _T("Name in registry not found!"); } } } int _tmain(int argc, _TCHAR* argv[]) { tstring val; function (val, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion"), _T("CommonFilesDir")); return 0; }
1,514,311
1,514,340
Removing from STL std::queue without destructing the removed object?
All the documentation I can find on the STL containers (both queue and list) say that for any of the remove functions the removed object's destructor is called. This means that I can't use std::queue any time I want a queue that's simply a list of objects needing some operation performed on them. I want to be able to add objects to the queue when they are waiting in line for me to do something to them. Then I want to remove them from it when I've finished with them, without destroying the object in question. This doesn't appear to be possible from the documentation I've read. Am I misreading the documentation? Is there another type of queue in the STL other than the basic "queue" that doesn't call the removed object's destructor on a call to pop_front? Edit to clarify: In my case I'm using a list of pointers. Something like this: dbObject *someObject; queue<dbObject *> inputQueue; inputQueue.push_back(someObject); ... dbObject *objectWithInput = inputQueue.front(); //handle object's input... inputQueue.pop_front(); // Remove from queue... destroyed now?
If you put pointers to objects in the queue (and any other STL container), the pointers won't get deleted when you remove them. To elaborate: when you use std::queue and remove an object the destructor of some_obj* is called. But the destructor for plain pointer (or any POD type - int, char, etc) is empty, no-op. The fine line here is that the destructor for some_obj* is very different from the destructor for some_obj.
1,514,392
1,514,441
Binding operator new?
I'd like to bind operator new (see example below). If the constructor doesn't have any arguments, it works fine, but if it does have arguments, I apparently have trouble getting the bind syntax correct. #include <map> #include <boost\function.hpp> #include <boost\lambda\lambda.hpp> #include <boost\lambda\construct.hpp> #include <boost\lambda\bind.hpp> enum TypeEnum { BarType, BazType }; class Foo { }; class Bar : public Foo { public: Bar(int x) { BarVal = x; } private: int barVal; }; class Baz : public Foo { public: Baz(int x) { bazVal = 2 * x; } private: int bazVal; }; class FooFactory { public: FooFactory() { // How does this work? factoryMap[BarType] = boost::lambda::bind(boost::lambda::new_ptr<Bar>(_1)); factoryMap[BazType] = boost::lambda::bind(boost::lambda::new_ptr<Baz>(_1)); } Foo* getFoo(TypeEnum type, int z) { return factoryMap[type](z); } private: std::map<TypeEnum, boost::function<Foo* (int)>> factoryMap; }; int main() { FooFactory fooFactory; Bar *newBar = static_cast<Bar*> (fooFactory.getFoo(BarType, 10)); return 0; }
This should do: factoryMap[BarType] = boost::lambda::bind(boost::lambda::new_ptr<Bar>(), boost::lambda::_1); factoryMap[BazType] = boost::lambda::bind(boost::lambda::new_ptr<Baz>(), boost::lambda::_1);
1,514,480
1,514,537
c++ overload operator==
I have a class with the following bool DistinctWord::operator==(const DistinctWord W) const { return strWord == W.strWord; } bool DistinctWord::operator==(const DistinctWord& W) const { return strWord == W.strWord; } I'm doing this in my program DistinctWord* wordOne = new DistinctWord("Test"); DistinctWord* wordTwo = new DistinctWord("Test"); if(*wordOne == *wordTwo) cout << "true"; else cout << "false"; I get this error error C2678: binary '==' : no operator found which takes a left-hand operand of type 'DistinctWord' (or there is no acceptable conversion) could be 'built-in C++ operator==(DistinctWord *, DistinctWord * )' I'm probably just not understanding the right way to overload. Sorry for the simple question. TIA
EDIT: OK, I've figured out your problem. It is the non-reference version of the operator==. It makes the operator== ambiguous. Simply remove it (as I originally suggested) and it'll work fine. EDIT: In response to your edit, you should still remove the first version of the operator== There is no need to make a copy of the object in question and then compare it. The second operator== looks reasonable and should work. Is there anything else you are leaving out? EDIT: The following compiles just fine for me using g++ 4.4.1: #include <iostream> struct DistinctWord { DistinctWord(const std::string &s) : strWord(s){} bool operator==(const DistinctWord& W) const { return strWord == W.strWord; } std::string strWord; }; int main() { DistinctWord* wordOne = new DistinctWord("Test"); DistinctWord* wordTwo = new DistinctWord("Test"); if(*wordOne == *wordTwo) std::cout << "true"; else std::cout << "false"; } If you are still having problems, then you are not showing all relevant code... First of all, where is the definition for DistinctWord and how does it relate to Word? Beyond that, you should do this: bool Word::operator==(const Word& W) const { return strWord == W.strWord; } and just remove the two operator=='s you currently have. The first is making a copy then comparing which is silly, and your second is comparing a modifiable reference and always returning true which doesn't really serve any purpose. This one should work fine.
1,514,497
1,514,506
Accessing members of an object that hasn't been initialized?
I'm not very familiar with C++ programming. I know the basics of programming in it (syntax, pointers, etc.) and I've built a few basic programs with it and done some basic debugging at work. I am puzzled by this line of code from Box2D, specifically the Box2dTest project from Cocos2D: // Define the ground body. b2BodyDef groundBodyDef; groundBodyDef.position.Set(0, 0); // bottom-left corner How is it that one can do this without having initialized groundBodyDef? I know this isn't an Objective-C thing because the C++ examples for Box2D itself are just like this.
groundBodyDef actually is initialized! I think you expected something along the lines of: b2BodyDef *groundBodyDef = new b2BodyDef(); which is actually still valid, but it is initialized on the heap. In your version, groundBodyDef is initialized on the stack, much like you would initialize an int on the stack. As it is called without parameters, the default constructor is used.
1,514,619
1,514,650
Can I declare a function that can take pointer to itself as an argument?
Reading a question in stackoverflow, I wondered whether it's possible to declare a function that takes a pointer to itself. I.e. to make such declaration of foo, for which the following would be correct: foo(foo); The simpliest idea is casting to another function pointer (can't cast to void*, since it may be smaller), so the function declaration looks like this: void foo(void (*)()); While that's OK in C (and will work with casting in C++), I wonder, whether it can be done without such hard "reinterpret" casting or losing type information. In other words, I want the following declaration: void foo( void (*)( void (*)( void (*) ( ... )))); but, of course, unlimited declarations are impossible. Naive typedefing doesn't help either. C++ templates are welcome, even if they make the calling code (foo(foo)) look a bit less succinct, but still finite. C-style answers that show, how one can drop type information without casting, or other tricks of that sort are, of course, interesting, but won't be accepted.
Generally I agree with Dario - making this on type level seems impossible. But you can use classes ("strategy pattern"): class A { void evil(A a) { // a pointer to A is ok too } }; You can even add operator(): void operator()(A a) { return evil(a); } Generally such things are better done in FP languages. Haskell version is simply: data Evil = Evil (Evil -> Integer) This uses a wrapper (Evil) that corresponds to using a class. From the questioner: what this answer lacked was the ability to pass several different functions as an argument of one of them. This can be solved either by making evil() virtual or by explicitly storing in the object a function pointer that implements it (which is basically the same). With this clarification, the answer is good enough to be accepted.
1,514,674
1,514,681
stl::find_if with user search
I was wondering if there was a way to use the stl::find_if to search for a user inputted value I don't know to do that without using any bad conventions(globals) or adding loads of extended code. For example, if a user inputs a int x for 10, then I want to search an vector of ints iterator = find_if(begin,end,pred) //but how does pred know the user inputted value?
The pred must be an instance of a type that has the overloaded () operator, so it can be called like a function. struct MyPred { int x; bool operator()(int i) { return (i == x); } }; (Using a struct for brevity here) std::vector<int> v; // fill v with ints MyPred pred; pred.x = 5; std::vector<int>::iterator f = std::find_if(v.begin(), v.end(), pred); Writing custom classes like this (with "loads" of code!) is cumbersome to say the least, but will be improved a lot in C++0x when lambda syntax is added.
1,514,747
1,587,317
What is different about the CMake command configure_file on Windows?
On linux I am using a command such as: configure_file(dot_alpha_16.bmp test/dot_samples/dot_alpha_16.bmp COPYONLY) to copy some unit test files to the build directory. On windows the files aren't getting copied. Is there a specific reason why this happens?
You have to specify the complete directory path. The following works on Windows and takes out-of-source builds into account too: configure_file(${CMAKE_CURRENT_SOURCE_DIR}/dot_alpha_16.bmp ${CMAKE_CURRENT_BINARY_DIR}/test/dot_samples/dot_alpha_16.bmp COPYONLY)
1,514,798
1,514,805
If Linked List and Array are fundamental data structures what type of data structure are tree, hash table, heap etc?
I was going through data structure online class and it was mentioned that linked list and array are fundamental data-structures and so my question is about Hash table, Heap, tree and graph are those not fundamental data structures and if not are they derived from any other data structure ? Thanks.
List and array could be considered fundamental because almost every single data structure is composed by pieces of these original data structures. Graphs for instance, can be array backed or list backed (usually for sparse graphs). But AFIAK as is many things in computer science it is not formalized what a "fundamental data structure" might mean mathematically.
1,514,844
1,514,848
What makes smartpointers better than normal pointers?
What makes smartpointers better than normal pointers?
They simplify the problem of resource management. Once you hold your resources within smart pointers they will release memory for you when they go out of scope applying RAII techniques. This has two main advantages: code is safer (less prone to resource leaks) and programming is easier as you do not need to remember in each part of your code whether the resource you are holding must be manually released.
1,515,100
1,515,116
Using a C++ library in an Objective-C app?
I am planning on learning Objective-C to write an OS X application but it will depend on a library written in C++. Can I interface with C++ in an Objective-C app? I'm new to desktop development. The C++ library will be used simply to analyze a file and return some data about that file. For example, in the libraries compiled example, in terminal you'd type ./xlsanalysis my_spreadsheet.xls and it returns: rows: 34 columns: 10 first row: "My Spreadsheet header" Can I include this library directly into the Objective-C app or interface with it some how?
For this purpose, there is Objective-C++, e.g. Objective-C plus C++ (or vice versa). From Objective-C++ files (e.g. .mm files), you have full access to all C++ functionality. Be careful when casting types from C++ to Objective-C, e.g. you should convert a C++ string to a NSString by using something like [NSString stringWithCString:cPlusPlusString.c_str()] The other direction would be string cPlusPlusString([objectiveCString cString]) (or cStringUsingEncoding:).
1,515,297
1,515,360
What creates the three close/minimize/maximize icons in the top corner of a window? (C++)
I am making a C++/Windows/DirectX program, and when it runs in windowed mode (using d3dpp.Windowed = (!FULLSCREEN); where FULLSCREEN is defined as 0), the three icons that are usually at the top of any window (minimize, maximize/restore, and close) are not there. Also, it's not like just an image with no border or anything, it looks identical to a normal window, minus the aforementioned three icons. So, what could cause a window to lose the three icons in the top corner without changing any other aspect of it?
You don't tell how the window is created for you. When programming plain Win32, you create windows with the CreateWindow() or CreateWindowEx() functions, which you pass some window style flags. The WS_MINIMIZEBOX and WS_MAXIMIZEBOX flags do what you'd expect, while the WS_SYSMENU flag controls both the addition of the close button and the window icon in the top left. If none of those three flags are set for the window, it will have no buttons.
1,515,399
1,515,407
Can you make custom operators in C++?
Is it possible to make a custom operator so you can do things like this? if ("Hello, world!" contains "Hello") ... Note: this is a separate question from "Is it a good idea to..." ;)
Yes! (well, sort of) There are a couple publicly available tools to help you out. Both use preprocessor code generation to create templates which implement the custom operators. These operators consist of one or more built-in operators in conjunction with an identifier. Since these aren't actually custom operators, but merely tricks of operator overloading, there are a few caveats: Macros are evil. If you make a mistake, the compiler will be all but entirely useless for tracking down the problem. Even if you get the macro right, if there is an error in your usage of the operator or in the definition of your operation, the compiler will be only slightly more helpful. You must use a valid identifier as part of the operator. If you want a more symbol-like operator, you can use _, o or similarly simple alphanumerics. CustomOperators While I was working on my own library for this purpose (see below) I came across this project. Here is an example of creating an avg operator: #define avg BinaryOperatorDefinition(_op_avg, /) DeclareBinaryOperator(_op_avg) DeclareOperatorLeftType(_op_avg, /, double); inline double _op_avg(double l, double r) { return (l + r) / 2; } BindBinaryOperator(double, _op_avg, /, double, double) IdOp What started as an exercise in pure frivolity became my own take on this problem. Here's a similar example: template<typename T> class AvgOp { public: T operator()(const T& left, const T& right) { return (left + right) / 2; } }; IDOP_CREATE_LEFT_HANDED(<, _avg_, >, AvgOp) #define avg <_avg_> Key Differences CustomOperators supports postfix unary operators IdOp templates use references rather than pointers to eliminate use of the free store, and to allow full compile-time evaluation of the operation IdOp allows you to easily specify several operations for the same root identifier
1,515,460
1,515,474
How to remove "NSBundle may not respond to '-pathForResource:ofType' " warning
I am trying to expose the pathForResource functionality to C++ from objective-c. However, I am very new to objective-c and have not been able to discern how to use a c string as an argument in objective-c. clearly I have the wrong idea here. how do i get pathForResource to use c strings as an argument? here is my function: static std::string getAssetPath(std::string name, std::string ending) { const char * nameChar = name.c_str(); const char * endingChar = ending.c_str(); NSString* assetPath = [NSBundle pathForResource:&nameChar ofType:&endingChar]; std::string str; str = std::string([assetPath cStringUsingEncoding: NSASCIIStringEncoding]); return str; }
NSString* nameChar = [NSString stringWithCString:name.c_str() encoding:NSUTF8StringEncoding]; NSString* endingChar = [NSString stringWithCString:ending.c_str() encoding:NSUTF8StringEncoding]; NSString* assetPath = [[NSBundle mainBundle] pathForResource:nameChar ofType:endingChar];
1,515,552
1,516,939
Global Constants vs. Enumeration
In terms of coding practice, in what contexts are global constants preferred to enumeration and vice versa? For example, let's say I needed a way to express a variety of tile sprites at a global scope. I could do... const int TILE_RED = 0; const int TILE_GREEN = 1; const int TILE_BLUE = 2; const int TILE_CENTER = 3; const int TILE_TOP = 4; const int TILE_TOPRIGHT = 5; const int TILE_RIGHT = 6; const int TILE_BOTTOMRIGHT = 7; const int TILE_BOTTOM = 8; const int TILE_BOTTOMLEFT = 9; const int TILE_LEFT = 10; const int TILE_TOPLEFT = 11; or enum Tile { TILE_RED, TILE_GREEN, TILE_BLUE, TILE_CENTER, TILE_TOP, TILE_TOPRIGHT TILE_RIGHT, TILE_BOTTOMRIGHT, TILE_BOTTOM, TILE_BOTTOMLEFT, TILE_LEFT, TILE_TOPLEFT }; Obviously we prefer constants and enums to macros, but what about when it comes down to constants and enums? What situations prefer what? I read here that constant objects pose a small risk of making your program slower, but I'd like to hear others' thoughts. I used this example in particular because it's a large set of related objects - the cat's pajamas for enumeration.
One nice thing about enums is that they're portable between C and C++, while const items can't be used in C in all the places you might like (Like array declarations). So for headers that I'd like to work in either C or C++ I have tended to use enums in preference to const declarations or macro definitions. Actually I've tended to use them regardless of whether the header is intended only for C++ or not (one less decision I have to think about). Having the type of the enum be ambiguous isn't a problem very often - if you're overloading based on various different integral types you'll have potential problems with enums, and in that case const items would probably be better. But I can't remember the last time I've needed different behavior for different types of the same number (ie., treating 5U differently than 5 or 5L). I think that type of overloading is only really seen in puzzle/interview types of problems, or it's code that'll breed bugs anyway whether you use enums or not. So bottom line is I'd prefer enums - but good luck getting your co-workers to stop using macros. Using macros for named constants is pretty well ingrained in the C/C++ culture and even though they pollute the namespace in a big way, there's not enough real word problems to convince many people to even think about changing the habit.
1,515,688
1,515,704
How to find performance bottlenecks in C++ code
I have a server application written in C++ and deployed in Cent OS. I haven't wrote any part of its code but i need to optimize its performance. Its current performance is acceptable for few amount of users but when the number of users increase the server's performance decrease dramatically. Are there any tools, techniques or best practices to find out the bottlenecks?
People typically use profilers to determine performance bottlenecks. Earlier SO questions asking for C++ profilers are here and here (depending on the operating system and compiler you use). For Linux, people typically use gprof, just because it comes with the system.
1,515,828
1,515,959
Getting the point of a catmull rom spline after a certain distance?
If I have a Catmull-Rom spline of a certain length how can I calculate its position at a certain distance? Typically to calculate the point in a catmull rom spline you input a value between 0 and 1 to get its position via proportions, how can I do this for distances? For example if my spline is 30 units long how can I get its position at distance 8? The reason I ask is because it seems with catmull rom splines giving points in the [0,1] domain does not guarantee that it will give you the point at that distance into the spline, for example if I input 0.5 into a catmull romspline of length 30 it does not mean I'll get the position at the distance of 15 of the spline unless the spline itself is in effect a straight line..
The usual way is to store length of each segment and then to find out the partial length of a segment you increment t by an epsilon value and calculate the linear distance between the 2 points until you hit your answer. Obviously the smaller your epsilon the better the result you get but it gives surprisingly good results. I used this method for moving at a constant speed along a catmul-rom and you cannot see it speed up and slow down ... it DOES move at a constant speed. Obviously depending on how tight your segments are your epsilon value will need to change but, in general, you can pick a "good enough" epsilon and everything will be fine. Findinf the answer non-iteratively is INCREDIBLY expensive (I have seen the derivation a while back and it was not pretty ;)). You will have to have a tiny epsilon value to get worse performance ...
1,515,899
1,515,903
Does C++ have an equivilent to Python's __setitem__
Just as the title asks, does C++ have the equivalent of Python's setitem and getitem for classes? Basically it allows you to do something like the following. MyClass anObject; anObject[0] = 1; anObject[1] = "foo";
basically, you overload the subscript operator (operator[]), and it returns a reference (so it can be read as well as written to)
1,516,017
17,925,540
Getting Connection timeout in OCCI
I need to test the connectivity if the Oracle::OCCI::Connection, and how can i get and set the connection timeout value? i read the documentation of Oracle OCCI but i can't find the required functions. Thanks in Advance.
Check this document: http://www.terralib.org/html/v410/classoracle_1_1occi_1_1_connection_pool.html Here you can see virtual unsigned int getTimeOut () const =0 and virtual void setTimeOut (unsigned int connTimeOut=0)=0 functions.
1,516,038
1,516,086
if given a 15 digit number whats the best way to find the next palindrome?
in c++ what will be the fastest logic to find next palindrome of a given 15 digit number? for example what will be the next palindrome of: 134567329807541 ?
Split the number into three parts, head, mid, tail 1345673 2 9807541 Reverse head and compare it to tail 3765431 If reverse(head) <= tail ( if they are equal the initial input is a palindrome, and you want the next ) If mid < 9, increment mid Else increment head part and set mid := 0 result := head mid reverse(head). 1345673 3 reverse(1345673) => 134567333765431
1,516,222
1,592,324
Xcode Documentation Set for C++ Standard Library
I've recently began using C++ with XCode and I'm starting to miss the integrated documentation that is available for Objective-C. I know that there is a way to generate documentation sets using Doxygen, but a readily available bundle would certainly be preferable... Is there an easy way to get XCode to search at least the standard C++ library documentation?
Using Doxygen is probably the easiest. The docs are quite straighforward and simple. Did you give it a shot? In looking at the other docs it looks like it should be there already. I was surprised it wasn't.
1,516,312
1,516,349
Registry - How to rename key in registry using C++?
How to rename key in registry using C++? I want rename key "Myapp\Version1" to "Myapp\Version2". I don't see any function in MSDN about renaming keys in registry.
There is no function to rename on older versions of windows, you need to copy/delete on your own AFAIK.
1,516,409
1,516,419
Is it possible?(c++)
Write pointer to string,delete pointer,and load pointer from string?
It's possible to do those operations, but they won't have the effect you're (probably) after. Writing the pointer to string will only store the pointer value, i.e. the address of the pointed-to object. This is a string of more or less constant length, like 0x7f2b93c91780 (on a 64-bit system). Naturally, this doesn't capture any of the state of the actual object. When you use delete on the pointer, the memory pointed at will be returned to the system; it's no longer yours to use. The pointer itself is not deleted, the operation only affects the memory being pointed at. Also, the pointer's value doesn't actually change when you use delete on it. Thus, there's no difference if you now re-load it by reading it in from a string stored somewhere else: it's still pointing at memory you no longer own, and thus can't read or write without invoking undefined behavior. Like PiotrLegnica suggested, you need to serialize the entire object into a string, and then re-create the object from the serialized version (de-serialize it).
1,516,476
1,516,544
How to create some class from dll(constructor in dll) in C++?
How to create some class from dll(constructor in dll)?(C++) or how to dynamically load class from dll?
Answering your question strictly, you need to add an extern "C" function that returns the result of the constructor: extern "C" foo* __declspec(dllexport) new_foo(int x) { return new foo(x); } Then in your source you can use GetProcAddr on "new_foo" to call the function.
1,516,563
1,516,654
const_cast in template. Is there a unconst modifier?
I have a template class like this: template<T> class MyClass { T* data; } Sometimes, I want to use the class with a constant type T as follows: MyClass<const MyObject> mci; but I want to modify the data using const_cast<MyObject*>data (it is not important why but MyClass is a reference count smart pointer class which keeps the reference count in the data itself. MyObject is derived from some type which contains the count. The data should not be modified but the count must be modified by the smart pointer.). Is there a way to remove const-ness from T? Fictional code: const_cast<unconst T>(data) ?
The simplest way here would be to make the reference count mutable. However, if you are interested in how it would work with the const_cast, then reimplementing boost's remove_const should be quite simple: template <class T> struct RemoveConst { typedef T type; }; template <class T> struct RemoveConst<const T> { typedef T type; }; const_cast<typename RemoveConst<T>::type*>(t)->inc();
1,516,574
1,516,643
Softball C++ question: How to compare two arrays for equality?
I am trying to compare two int arrays, element by element, to check for equality. I can't seem to get this to work. Basic pointer resources also welcome. Thank you! int *ints; ints = new int[10]; bool arrayEqual(const Object& obj) { bool eql = true; for(int i=0; i<10; ++i) { if(*ints[i] != obj.ints[i]) eql = false; } return eql; }
When you do if(*ints[i] != obj.ints[i]), what you are comparing is the address pointed by ints[i] with the content of obj.ints[i], instead of the content of ints[i] itself. That is because the name of an array is already a pointer to the first element of an array, and when you add the subscript, you will look for the ith position after the first in that array. That's why you don't need the *. The correct is: int *ints; ints = new int[10]; bool arrayEqual(const Object& obj) { bool eql = true; for(int i=0; i<10; ++i) { if(ints[i] != obj.ints[i]) eql = false; } return eql; } Hope I helped!
1,516,607
1,516,676
Why and Where do we use down casting?
Are there any cases where we do down casting of objects? If we do, why? I have observed a way of hiding implementation using the below code. Is this the correct way to do? Is there any better way to achieve the same. class A{ public: A(); virtual ~A(); //exposed virtual functions }; class AImpl : public A{ public: AImpl(A *obj); virtual ~AImpl(); //exposed virtual functions++ }; class Helper{ //utility class so i am making constructor and assignment operator as private public: static bool doWork(A *obj){ AImpl *objImpl = dynamic_cast<AImpl *> (obj); return doWork(objImpl); // some internal function } private: Helper(); Helper(const Helper& obj); const Helper& operator=(const Helper& obj); }; The question still does not makes sense. I agree. I still have not figured out a proper way of hiding the implementation details from the client. UncleBens I termed this thing wrongly as Object slicing. Basically, I was referring to this (Object Slicing) as the information related to derived part is missing. S.Soni Thanks for giving a wonderful explaination. Now, I can really put forward question. Consider a clients perspective. The only class which are visible to him is class A and the Helper class (because I have hidden implementation behind AImpl Client has to write the following code as he is unaware of AImpl class int main(){ A *a = new A(); Helper.doWork(a); // ... } As you said AImpl * in this case will actually be pointing to the base class object, which is wrong (you have explained it with a great example), so this approach of hiding implementation is not correct. Any attempt to access a derived class member function will result in a crash (and correctly so). How should I go about hiding the implementation in this case? This is a design problem now?
**Are there any cases where we do down casting of objects** The purpose of dynamic_cast is to perform casts on polymorphic types. For example, given two polymorphic classes Band D, with D derived from B, a dynamic_cast can always cast a D* pointer into a B* pointer. This is because a base pointer can always point to a derived object. But a dynamic_cast can cast a B* pointer into a D* pointer only if the object being pointed to actually is a D object. **`Is there any better way to achieve the same`** Perhaps the most important of the new casting operators is dynamic_cast. The dynamic_cast performs a run-time cast that verifies the validity of a cast. 1) Your class is not polymorphic.A class that declares or inherits a virtual function is called a polymorphic class 2) Syntax of dynamic_cast is dynamic__cast (expr) 1st Edit : Try like this , it will work class A { public: A(); virtual ~A();// Notice here i have put virtual }; class AImpl : public A { public: AImpl(A *obj); ~AImpl(); }; class Helper { public: Helper(){} static bool doWork(A *obj) { AImpl *objImpl = dynamic_cast<AImpl*> (obj); return true; } }; Study this example : class Base { public: virtual void f() { cout << "Inside Base\n"; } // ... }; class Derived: public Base { public: void f() { cout << "Inside Derived\n"; } }; int main() { Base *bp, b_ob; Derived *dp, d_ob; dp = dynamic_cast<Derived *> (&d_ob); if(dp) { cout << "Cast from Derived * to Derived * OK.\n"; dp->f(); } else cout << "Error\n"; cout << endl; bp = dynamic_cast<Base *> (&d_ob); if(bp) { cout << "Cast from Derived * to Base * OK.\n"; bp->f(); } else cout << "Error\n"; cout << endl; bp = dynamic_cast<Base *> (&b_ob); if(bp) { cout << "Cast from Base * to Base * OK.\n"; bp->f(); } else cout << "Error\n"; cout << endl; dp = dynamic_cast<Derived *> (&b_ob); if(dp) cout << "Error\n"; else cout << "Cast from Base * to Derived * not OK.\n"; cout << endl; bp = &d_ob; // bp points to Derived object dp = dynamic_cast<Derived *> (bp); if(dp) { cout << "Casting bp to a Derived * OK\n" << "because bp is really pointing\n" << "to a Derived object.\n"; dp->f(); } else cout << "Error\n"; cout << endl; bp = &b_ob; // bp points to Base object dp = dynamic_cast<Derived *> (bp); if(dp) cout << "Error"; else { cout << "Now casting bp to a Derived *\n" << "is not OK because bp is really \n" << "pointing to a Base object.\n"; } cout << endl; dp = &d_ob; // dp points to Derived object bp = dynamic_cast<Base *> (dp); if(bp) { cout << "Casting dp to a Base * is OK.\n"; bp->f(); } else cout << "Error\n"; return 0; }
1,516,622
1,516,648
What does vectorization mean?
Is it a good idea to vectorize the code? What are good practices in terms of when to do it? What happens underneath?
Vectorization means that the compiler detects that your independent instructions can be executed as one SIMD instruction. Usual example is that if you do something like for(i=0; i<N; i++){ a[i] = a[i] + b[i]; } It will be vectorized as (using vector notation) for (i=0; i<(N-N%VF); i+=VF){ a[i:i+VF] = a[i:i+VF] + b[i:i+VF]; } Basically the compiler picks one operation that can be done on VF elements of the array at the same time and does this N/VF times instead of doing the single operation N times. It increases performance, but puts more requirement on the architecture.
1,516,659
1,516,688
How do I count how many milliseconds it takes my program to run?
This will show how many seconds: #include <iostream> #include <time.h> using namespace std; int main(void) { int times,timed; times=time(NULL); //CODE HERE timed=time(NULL); times=timed-times; cout << "time from start to end" << times; } This will show how many ticks: #include <iostream> #include <time.h> using namespace std; int main(void) { int times,timed; times=clock(); //CODE HERE timed=clock(); times=timed-times; cout << "ticks from start to end" << times; } How do I get milliseconds?
Refer to question "Convert Difference between 2 times into Milliseconds" on Stack Overflow. Or use this: static double diffclock(clock_t clock1,clock_t clock2) { double diffticks=clock1-clock2; double diffms=(diffticks)/(CLOCKS_PER_SEC/1000); return diffms; }
1,516,696
1,516,716
How to overload opAssign operator "globally" in C++
Just curious about how to overload them. The opAssign operators are like addAssign(+=) and subAssign(-=). "globally" means they are not overloaded as member functions, but just a operator act on operands For these opAssign operators, they are binary operators.(they receive two operands) Therefore two parameters are needed. I found no examples on the web.....
Here's a trivial example of defining operator+=: struct Foo{ int x; }; Foo& operator+=(Foo& lhs, const Foo& rhs) { lhs.x += rhs.x; return lhs; }
1,516,730
1,557,182
Impersonation and Registry Manipulation in Vista\Win7
I need to create a program that has access to HKLM when running in a non-admin session. I have access to the admin credentials so impersonation seems to be an option.The sequence of Win32 calls is: LogonUser ImpersonateLoggedOnUser RegOpenKeyEx RegCreateKeyEx The key is successfully created on XP/2003 and fails with 'Access Denied' on Vista/Win7. I am running as the same default domain user and impersonating the same domain admin in each of the scenarios. The 'Access Denied' is being generated by RegCreateKeyEx and obviously the key isn't being created. Anyone have a clue to why this is happening?
The way to accomplish this is through multiple processes as Murray and Anders suggested. First you launch a process to launches another process with the CreateProcessAsLoggedOnUser with Admin credentials. Then you have to launch ANOTHER process using the ShellExecute function with "runas" specified as the verb. This allows for impersonation and elevation without a UAC dialog.
1,516,756
1,516,775
Class naming and namespaces
Will using same class name within multiple namespaces get me into trouble? I also try to remove dependency to math library. What do you think about following design. first file #define MATH_RECTANGLE_EXISTS namespace math { class Rectangle : Object2D { public: float perimeter(); float area(); float x,y,w,h; }; } other file #define GRAPHIC_RECTANGLE_EXISTS #ifndef MATH_RECTANGLE_EXISTS //is this a good idea to remove dependency? namespace math { class Rectangle { public: float x,y,w,h; } } #endif namespace graphics { class Rectangle : math::Rectangle { public: void Draw(Canvas &canvas); void Translate(float x, float y); }; } EDIT What about this approach to remove dependency? ** 1st file** namespace common { class Rectangle { float x,y,w,h; }; } math lib file #define MATH_RECTANGLE_EXISTS namespace math { class Rectangle : public common::Rectangle, public Object2D { public: float perimeter(); float area(); }; } graphic file #define GRAPHIC_RECTANGLE_EXISTS namespace graphics { #ifndef MATH_RECTANGLE_EXISTS class Rectangle : public math::Rectangle { #else class Rectangle : public common::Rectangle { #endif public: void Draw(Canvas &canvas); void Translate(float x, float y); }; } Thanks in advance.
I don't see the problem with reusing the same identifier within different namespaces, that was they were created for after all. However I would strongly urge you NOT to 'simulate' the inclusion of math::Rectangle. If you need the file then include it, but what you are doing is called copy/paste programming, and it leads to a good number of problems, essentially because your two pieces of code are not synchronized so any bug fix / feature addition to one is not reported on the other. EDIT: answer to the Edit ;) It is not clear from the comments so I will state it: If you need the dependency (because you really USE the functionality offered), then you HAVE to include the header. On the other hand, if you only use inheritance to get something that have 4 corners and nearly no method, then you're better up rolling a new Rectangle class with the minimum functionality. I can think of an edge case though. I am under the impression that you are not so much interested in the functionality but in fact interested in the possibility of reusing the methods in the Math library that have been tailored to take a math::Rectangle as a parameter. According to Herb Sutter (in C++ Coding Standards I think), the free functions that are bundled with a class are part of the class public interface. So if you want those classes, you actually need the inheritance. Now I can understand that you may have some reluctance in including a library that may be huge (I don't know your Math library). In this case you could consider splitting the Math library in two: A MathShapes library, comprising the basic shapes and the methods that act upon them A Math library, which includes MathShapes and add all the other stuff This way you would only depend on the MathShapes library. On the other hand, if you absolutely do not want the dependency, then a blunt copy/paste will do, but your solution of testing the presence of Math::Rectangle by testing the presence of its header guard is ill-fitted: It only works if you get the header guard correctly AND if the include is actually performed BEFORE the include of Graphics::Rectangle Note that in the case in which Graphics::Rectangle is included before Math::Rectangle you may have some compilation issues... So make up your mind on whether or not you want the dependency.
1,516,842
1,516,991
What book or online resource do you suggest to learn programming C++ in Linux?
I have years of C++ programming experience in Windows. Now I need to program some applications for Linux. Is there any resource that helps me quickly get the required information about Linux technologies available to C++ developers?
Programming in C++ under Linux isn't all that different at the core. Linux compilers are generally more standard's conforming than MSVC; however, that is changing as MSVC is becoming a better compiler. The difference is more from the environment and available libraries. Visual Studio isn't available (obviously) but some other environments like Visual SlickEdit and Eclipse are available on both. The build system is widely varied and will probably be dictated by your preference between Gnome, KDE, or the ever-present command line. Personally, I find the latter to be the cleanest and most consistent. If you end up at the command line, then learn GNU Make and pick up a copy of GNU Autoconf, Automake, and Libtool. This will introduce the GNU command line development stack pretty nicely. Debugging is a lot different being that VS provides a nice GUI debugging environment. Most Linux environments simply wrap a command line debugger (usually gdb) with a GUI. The result is less than satisfactory if you expect a nicely integrated debugger. I would recommend getting comfortable with gdb. There are some decent tutorials for gdb online. Just google for a bunch of them. Once you get a little comfortable, read the online manual for the really neat stuff. The other choice is to use whatever development environment is packaged with your windowing system or to use something like Eclipse and some C++ plug-in As for books on the subject, Advanced Programming in the UNIX Environment is a must-read. UNIX Systems Programming is also a good read since it gives you a solid grounding in shells, processes, and what not. I would recommend both the POSIX Programmer's Guide and POSIX.4 Programmer's Guide since they give you a lot of the systems programming stuff. With all of that said, enjoy your foray into an operating system that really cater to programmers ;)
1,516,919
1,516,966
Declaring and initializing a variable in a Conditional or Control statement in C++
In Stroustrup's The C++ Programming Language: Special Edition (3rd Ed), Stroustrup writes that the declaration and initialization of variables in the conditionals of control statements is not only allowed, but encouraged. He writes that he encourages it because it reduces the scope of the variables to only the scope that they are required for. So something like this... if ((int i = read(socket)) < 0) { // handle error } else if (i > 0) { // handle input } else { return true; } ...is good programming style and practice. The variable i only exists for the block of if statements for which it is needed and then goes out of scope. However, this feature of the programming language doesn't seem to be supported by g++ (version 4.3.3 Ubuntu specific compile), which is surprising to me. Perhaps I'm just calling g++ with a flag that turns it off (the flags I've called are -g and -Wall). My version of g++ returns the following compile error when compiling with those flags: socket.cpp:130: error: expected primary-expression before ‘int’ socket.cpp:130: error: expected `)' before ‘int’ On further research I discovered that I didn't seem to be the only one with a compiler that doesn't support this. And there seemed to be some confusion in this question as to exactly what syntax was supposedly standard in the language and what compilers compile with it. So the question is, what compilers support this feature and what flags need to be set for it to compile? Is it an issue of being in certain standards and not in others? Also, just out of curiosity, do people generally agree with Stroustrup that this is good style? Or is this a situation where the creator of a language gets an idea in his head which is not necessarily supported by the language's community?
It is allowed to declare a variable in the control part of a nested block, but in the case of if and while, the variable must be initialized to a numeric or boolean value that will be interpreted as the condition. It cannot be included in a more complex expression! In the particular case you show, it doesn't seem you can find a way to comply unfortunately. I personally think it's good practice to keep the local variables as close as possible to their actual lifetime in the code, even if that sounds shocking when you switch from C to C++ or from Pascal to C++ - we were used to see all the variables at one place. With some habit, you find it more readable, and you don't have to look elsewhere to find the declaration. Moreover, you know that it is not used before that point. Edit: That being said, I don't find it a good practice to mix too much in a single statement, and I think it's a shared opinion. If you affect a value to a variable, then use it in another expression, the code will be more readable and less confusing by separating both parts. So rather than using this: int i; if((i = read(socket)) < 0) { // handle error } else if(i > 0) { // handle input } else { return true; } I would prefer that: int i = read(socket); if(i < 0) { // handle error } else if(i > 0) { // handle input } else { return true; }
1,516,958
1,517,195
Could someone please explain the difference between a "reference" and a "pointer" in this case?
When I read litb answer to this question, I learned that passing an array by reference allows us to obtain its size. I just played little bit with code, and tried to pass a "function" by reference and surprisingly (at least for me), this code compiles: void execute( void (&func)() ) // func is passed by reference! { func(); } Is there any difference between the last function, and this one: void execute( void (*func)() ) // func is passed by pointer! { func(); } I tried it using VC2008, and it produces different output in each case. The strange thing is that the compiler optimizes the code better in case of a function pointer: void print() { std::cout << "Hello References!"; } void execute( void (&func)() ) // optimized { func(); } int main() { 00291020 call print (291000h) } ========================================= // In this case, the compiler removes all function calls in the code! void print() // optimized! { std::cout << "Hello Pointers!"; } void execute( void (*func)() ) // optimized { func(); } int main() { 002F1005 push offset string "Hello References!" (2F2124h) 002F100A push eax 002F100B call std::operator<<<std::char_traits<char> > (2F1150h) } There has to be a difference, although I don't see it, right? Note: the code was compiled using VC2008, with /O2 and /Ot turned on. EDIT:: I am really interested about any difference between function references and function pointers. I examined the produced assembly code just to see how it is translated in each case.
For the language difference (keeping only the function declarations below, since that's what's important only) void execute( void (&func)() ); void g(); int main() { void (*fp)() = g; execute(fp); // doesn't work execute(&g); // doesn't work either execute(g); // works } It doesn't work, because it wants a function, not a function pointer. For the same reason that array answer rejects a pointer, this rejects a pointer too. You have to pass "g" directly. For templates, it matters too template<typename T> void execute(T &t) { T u = t; u(); } template<typename T> void execute(T t) { T u = t; u(); } Those two are very different from one another. If you call it with execute(g); like above, then the first will try to declare a function and initialize it with t (reference to g). The generated function would look like this void execute(void(&t)()) { void u() = t; u(); } Now you can initialize references and pointers to functions, but of course not functions itself. In the second definition, T will be deduced to a function pointer type by template argument deduction, and passing a function will convert it to that pointer parameter type implicitly. So everything will go fine. I don't know why MSVC treats them differently for inlining - but i also suspect it's because function references appear more seldom.
1,516,972
1,517,027
UDP socket port allocation failure
I am creating a winsock UDP program. code i am using is shown below. I am always getting port assignment error. I am not able to understand why port always allocated is zero. If some can help me with this.... void UDPecho(const char *, const char *); void errexit(const char *, ...); #define LINELEN 128 #define WSVERS MAKEWORD(2, 0) void main(int argc, char *argv[]) { char *host = "localhost"; char *service = "echo"; WSADATA wsadata; switch (argc) { case 1: host = "localhost"; break; case 3: service = argv[2]; /* FALL THROUGH */ case 2: host = argv[1]; break; default: fprintf(stderr, "usage: UDPecho [host [port]]\n"); exit(1); } if (WSAStartup(WSVERS, &wsadata)) errexit("WSAStartup failed\n"); UDPecho(host, service); WSACleanup(); exit(0); } void UDPecho(const char *host, const char *service) { char buf[LINELEN+1]; SOCKET s; int nchars; struct hostent *phe; struct servent *pse; struct protoent *ppe; struct sockaddr_in sin, my_sin; int type, status, client_port, size; char *transport = "udp"; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; /* Map service name to port number */ if ( pse = getservbyname(service, transport) ) sin.sin_port = pse->s_port; else if ( (sin.sin_port = htons((u_short)atoi(service)))== 0) errexit("can't get \"%s\" service entry\n", service); /* Map host name to IP address, allowing for dotted decimal */ if ( phe = gethostbyname(host) ) memcpy(&sin.sin_addr, phe->h_addr, phe->h_length); else if ( (sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE) errexit("can't get \"%s\" host entry\n", host); printf("Our target server is at address %s\n", inet_ntoa(sin.sin_addr)); printf("The size of an FD set is %d\n", sizeof(FD_SET)); /* Map protocol name to protocol number */ if ( (ppe = getprotobyname(transport)) == 0) errexit("can't get \"%s\" protocol entry\n", transport); /* Use protocol to choose a socket type */ if (strcmp(transport, "udp") == 0) type = SOCK_DGRAM; else type = SOCK_STREAM; /* Allocate a socket */ s = socket(PF_INET, type, ppe->p_proto); if (s == INVALID_SOCKET) errexit("can't create socket: %d\n", GetLastError()); size = sizeof(sin); memset(&my_sin, 0, sizeof(sin)); getsockname (s, (struct sockaddr *) &my_sin, &size); client_port = ntohs(my_sin.sin_port); if (client_port != 0) printf ("We are using port %2d\n", client_port); else { printf("No port assigned yet\n"); } } void errexit(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); WSACleanup(); exit(1); }
UDP doesn't bind to the listening port until you either issue a sendto() or a bind() on the socket. The latter lets you select the port that you want to listen on. Sendto(), on the other hand, will pick an ephemeral port for you. I would expect that the port will remain zero until you do one of these two things. Clarification I looked into this a little more after some of the comment. According to the Single UNIX Specification the result of calling socket() is an unbound socket. A socket is bound explicitly by calling bind() or implicitly sendto(). Think of a socket's name as a tuple containing its (Address Family, Protocol, local IP Address, and local Port Number). The first two are specified in the socket() call and the last two by calling bind(). In the case of connectionless protocols, a call to sendto() on a disconnected socket will result in an implicit bind to an OS chosen port number. The most surprising thing is that the only reference that I can find to this behavior is in the remarks section of the Microsoft documentation for sendto(). If the socket is unbound, unique values are assigned to the local association by the system and the socket is then marked as bound. An application can use getsockname (Windows Sockets) to determine the local socket name in this case. The Single UNIX Specification for getsockname() states: If the socket has not been bound to a local name, the value stored in the object pointed to by address is unspecified. It seems that a successful return with an unspecified result is the "standard" behavior... hmmm... The implementations that I have tried all return successfully with a socket address of 0.0.0.0:0 which corresponds to INADDR_ANY with an unspecified port. After calling either bind() or sendto(), getsockname() returns a populated socket address though the address portion might still be INADDR_ANY.
1,517,084
1,517,116
Bash input/output in C++
I'm writing program in C++ (for XAMPP communication) and I want to execute command which I have in strings (I know that this is simply system("command")) but I want to get the output from bash to C++ to string. I've founded several threads about this, but no which solved Bash -> C++.
You can call the FILE *popen(const char *command, const char *mode) function. Then, you can read the file it returns to get the output of your call. It's like using a pipe to redirect the output of the command you used to a file in the hard drive and then read the file, but you don't get to create a file in the hard drive. The documentation of the popen() is here.
1,517,483
1,517,515
How to use hash_map with char* and do string compare?
I was using std::hash_map<char*,T> and somehow managed to make it work but have now discovered that the default compare function, euqal_to<char*> does a pointer compare rather than a string compare. I've fixed this by making my own compare type (using C's strcmp and it's about 5 LOC) but I'd be slightly shocked if there wasn't one already as part of the STL. So, is there a comparator for doing string comparison? Related link
Well, std::strcmp is defined by C++ when you do #include <cstring>. The example in SGI's hash_map doc provides a strcmp-based example of making your own equality-testing function for char*'s (quoting from beginning of the SGI doc): struct eqstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) == 0; } }; I have to say I agree with the author of the link in your post, where he says that it is already a mistake for hash_map<char*> to use by default a string-based hash<char*>. But I usually use hash_maps (or, lately, boost::unordered_maps) on C++ std::strings for this kind of thing anyway.
1,517,549
1,529,489
Transparent sprites in c++ with Allegro
I'm learning to use Allegro. I'm trying to make my character cut out. How do I key out a certain color from my bitmap? which way is used for allegro? Thanks
These might be places to start: http://www.allegro.cc/manual/api/blitting-and-sprites/draw_trans_sprite http://wiki.allegro.cc/index.php?title=Alpha_channel#Drawing_to_the_alpha_channel_in_Allegro
1,517,566
1,517,634
How to draw a (bezier) path with a fill color using GDI+?
I am making a SVG renderer for Windows using the Windows API and GDI+. SVG allows setting the 'fill' and 'stroke' style attributes on a Path. I am having some difficulty with the implementation of the 'fill' attribute. The following path represents a spiral: <svg:path style="fill:yellow;stroke:blue;stroke-width:2" d="M153 334 C153 334 151 334 151 334 C151 339 153 344 156 344 C164 344 171 339 171 334 C171 322 164 314 156 314 C142 314 131 322 131 334 C131 350 142 364 156 364 C175 364 191 350 191 334 C191 311 175 294 156 294 C131 294 111 311 111 334 C111 361 131 384 156 384 C186 384 211 361 211 334 C211 300 186 274 156 274" /> The fill color is yellow, and it should fill the entire shape, this is however what I get: My GDI+ calls look like this: Gdiplus::GraphicsPath bezierPath; bezierPath.AddBeziers(&gdiplusPoints[0], gdiplusPoints.size()); g.FillPath(&solidBrush, &bezierPath); g.DrawPath(&pen, &bezierPath); Apparently the code is correct for drawing the shape, but not for filling it. Can anyone help me in figuring out what's going wrong?
Try to set the FillMode property of your GraphicsPath to FillMode::Winding, an alternate filling method that should suits your needs.
1,517,678
1,517,695
Is this C++ reassignment valid?
Sorry for the basic question, but I'm having trouble finding the right thing to google. #include <iostream> #include <string> using namespace std; class C { public: C(int n) { x = new int(n); } ~C( ) { delete x; } int getX() {return *x;} private: int* x; }; void main( ) { C obj1 = C(3); obj1 = C(4); cout << obj1.getX() << endl; } It looks like it does the assignment correctly, then calls the destructor on obj1 leaving x with a garbage value rather than a value of 4. If this is valid, why does it do this?
If there is a class C that has a constructor that takes an int, is this code valid? C obj1(3); obj1=C(4); Assuming C has an operator=(C) (which it will by default), the code is valid. What will happen is that in the first line obj1 is constructed with 3 as a the parameter to the constructor. Then on the second line, a temporary C object is constructed with 4 as a parameter and then operator= is invoked on obj1 with that temporary object as a parameter. After that the temporary object will be destructed. If obj1 is in an invalid state after the assignment (but not before), there likely is a problem with C's operator=. Update: If x really needs to be a pointer you have three options: Let the user instead of the destructor decide when the value of x should be deleted by defining a destruction method that the user needs to call explicitly. This will cause memory leaks if the user forgets to do so. Define operator= so that it will create a copy of the integer instead of a copy of the value. If in your real code you use a pointer to something that's much bigger than an int, this might be too expensive. Use reference counting to keep track how many instances of C hold a pointer to the same object and delete the object when its count reaches 0.
1,517,854
1,517,894
priority_queue<> comparison for pointers?
So I'm using the STL priority_queue<> with pointers... I don't want to use value types because it will be incredibly wasteful to create a bunch of new objects just for use in the priority queue. So... I'm trying to do this: class Int { public: Int(int val) : m_val(val) {} int getVal() { return m_val; } private: int m_val; } priority_queue<Int*> myQ; myQ.push(new Int(5)); myQ.push(new Int(6)); myQ.push(new Int(3)); Now how can I write a comparison function to get those to be ordered correctly in the Q? Or, can someone suggest an alternate strategy? I really need the priority_queue interface and would like to not use copy constructors (because of massive amounts of data). Thanks EDIT: Int is just a placeholder/example... I know I can just use int in C/C++ lol...
One option that will surely work is to replace Int* with shared_ptr<Int> and then implement operator< for shared_ptr<Int> bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b) { return a->getVal() < b->getVal(); }
1,517,868
1,517,874
Performance of Java 1.6 vs C++?
With Java 1.6 out can we say that performance of Java 1.6 is almost equivalent to C++ code or still there is lot to improve on performance front in Java compared to C++ ? Thanks.
Debian likes to conduct benchmarks on this sort of thing. In their case, it appears that Java is about half as fast and consumes 2-18 times as much memory as C++.
1,517,881
1,517,909
c++ global constants issue
We have these set of "utility" constants defined in a series of file. The problem arises from the fact that TOO MANY files include these global constant files, that, if we add a constant to one of those files and try to build, it builds the whole entire library, which takes up more than an hour. Could anyone suggest a better way for this approach? That would be greatly appreciated.
First, if you are defining them directly in the header, I'd suggest instead delcaring them extern const, and then defining them in a cpp file: //in .hpp: extern const std::string foo; //in .cpp: const std::string foo = "FOO"; That way, at least definitions can be changed without a rebuild. Second, examine where they are being included. If the constant file is being included in a low level header, can the include be moved to the cpp instead? Removing it might lower the coupling so it doesn't have to rebuild as much. Third, break up that file. I'd suggest mapping out a structure you'd eventually want, start adding new constants to the new structure instead of the old file. Eventually (when you are sure you've got the structure you want), refactor the old file into the new structure, and make the old file include the entire structure. Finally, go through and remove all includes of the old file, pointing them at the appropriate new sections. That'll break up the refactoring so you don't have to do it all at once. And fourth, you might be able to trick your compiler into not rebuilding if the header file changes. You'd have to check your compiler's documentation, and it might be unsafe, so you'd occasionally want to add full builds as well.
1,518,480
1,518,488
Compile (?) issue. Visual studio c++ 2008
There's an app that I use on an XP netbook for tuning a car. It was working just fine. Then I needed to make a simple modification (output to STDOUT instead of to file) so I got the source from the author. My netbook doesn't have the space for a compiler. I have Visual Studio C++ 2008 on a Windows 7 desktop. I made the adjustments, compiled and tested on the desktop and it worked perfecty. So then I copied the executable to the netbook and it won't run "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem" Original (precompiled) exe works fine. To rule out my changes, I compiled the source without the mods and it still didn't work. The executable works fine on the 7 machine as well as another Win Vista machine I tried. So its obviously something with the XP machine and the way the executable is compiled. I really have no idea how this stuff works so I don't know what to try.
Its because a dependency / DLL compiled into your application doesn't exist on the platform you are running on. Open windows event viewer and view the application log. There will be an entry for the error and the name of the DLL which is missing. Copy / Install that DLL on your target platform. I would guess your vc runtime has changed with visual studio 2008 and you need to copy the latest version to your target platform. If you dont know where to get the dependency DLL, post the name here and we can see what we can do about it.
1,518,534
1,518,596
Multiple output operators?
is it possible to define multiple output operators for an enum? I want to use this std::ostream& operator<< (std::ostream& os, my_enum e); operator to (1) print a human readable text and to (2) convert it to some code for storing in a database. Thanks
Create wrappers which will return some object instead of ostream& which will handle printing. In your case it will object for printing humand-readable value and object for printing database code. Here's rough example which prints human-readable form and integer form. ostream_enum_wrapper_human class with its operator << is used for printing human-readable form, class ostream_enum_wrapper_int with its << is used for printing integer code. To switch from ostream& to wrapper, operator << (ostream&, wrappertag) is used, which wraps ostream object inside of wrapper and returns wrapped object. So next << operator is called on wrapper object, not on ostream&, and wrapper class knows how to print value. #include <iostream> using namespace std; class ostream_enum_wrapper_human { public: ostream& out; ostream_enum_wrapper_human(std::ostream& _out) : out(_out){} }; class ostream_enum_wrapper_int { public: std::ostream& out; ostream_enum_wrapper_int(std::ostream& _out) : out(_out){} }; enum T{zero,one,two}; struct human_readable{} HumanReadable; ostream_enum_wrapper_human operator << (ostream& out, human_readable){ return ostream_enum_wrapper_human(out); } struct print_int{} PrintInt; ostream_enum_wrapper_int operator << (ostream& out, print_int){ return ostream_enum_wrapper_int(out); } ostream& operator << (ostream_enum_wrapper_human out, T t) { switch(t) { case zero: out.out << "zero"; break; case one: out.out << "one"; break; case two: out.out << "two"; break; } return out.out; } ostream& operator << (ostream_enum_wrapper_int out, T t) { return out.out << static_cast<int>(t); } int main() { cout << HumanReadable << zero << PrintInt << zero << HumanReadable << two; } prints zero0two
1,518,555
1,518,570
Casting to one class and calling function from sibling class?
I'm getting a pointer to a base class (which is actually a pointer to some derived class). Then I want to call a function on that derived class, but I don't know which one it is. class Base { }; class DerivedOne : public Base { public: void functionA() { int x = 0; } }; class DerivedTwo : public Base { public: void functionA() { int x = 0; } }; int main() { Base* derivedTwoPtr = new DerivedTwo(); reinterpret_cast<DerivedOne*>(derivedTwoPtr)->functionA(); return 0; } This works as I want, but I have to say it looks rather dodgy. Is it defined behavior? If not, is there a legal way to dynamically resolve this?
Hey, don't do that. That's what virtual methods are for. class Base { public: virtual void functionA()=0; }; class DerivedOne : public Base { public: virtual void functionA() { int x = 0; } }; class DerivedTwo : public Base { public: virtual void functionA() { int x = 0; } }; int main() { Base* derivedTwoPtr = new DerivedTwo(); derivedTwoPtr->functionA(); return 0; }
1,518,710
1,518,724
in-class initialization of non-integral static data
So I just learned via a compiler error that in-class initialization of arrays is invalid (why?). Now I would like to have some arrays initialized in a template class, and unfortunatly the contents depend on the template parameter. A condensed testcase looks like this: template<typename T> struct A { T x; static const int len = sizeof(T); // this is of course fine static const int table[4] = { 0, len, 2*len, 3*len }; //this not } Any idea how to pull out the constant array? EDIT: Added the 'int's.
Just as you'd do it without templates; put the initialization outside the class' declaration: template<class T> const int A<T>::table[4] = { 0, len, 2*len, 3*len };
1,519,215
1,519,229
Does C++ have standard queue?
I know that there's a standard library vector in C++. Is there a queue? An online search suggests there might be, but there's not much about it if there is one. Edit: All right. Thanks a ton guys.
std::queue (container adaptor)
1,519,368
1,519,519
C++ : has_trivial_X type traits
The boost library, and it seems the upcoming C++0x standard, define various type trait templates to differentiate between objects which have trivial constructors, copy constructors, assignment, or destructors, versus objects which don't. One of the most significant uses of this is to optimize algorithms for certain types, e.g. by using memcpy. But, I don't understand the real practical difference between all the various has_trivial_X templates. The C++ standard only defines two broad categories of types that concern us here: POD and non-POD. A type is non-POD if it has a defined constructor, copy constructor, assignment operator, or destructor. In other words, anything that's not a built-in type, or a C-struct of built-in types, is not a POD. So what's the point of differentiating between, for example, has_trivial_assign and has_trivial_constructor? If an object has a non-trivial assignment operator OR a non-trivial constructor it's not a POD. So under what circumstances would it be useful to know that an object has a trivial assignment operator, but a non-trivial constructor? In other words, why not define a single type-trait template, is_pod<T>, and be done with it?
The POD type definition got relaxed in C++0A. A type may have a non-trivial-constructor, but may have a trivial assignment operator. E.g. struct X { X() : y( -1 ) {} X( int k, int v ) : y( k * v ) {} int y; }; X could be 'memcopy'-ied, but not trivially constructed.
1,519,635
1,519,651
Problem with std::multimap
I've got the following : enum Type { One = 0, Two}; class MySubClass { private: MySubClass(); // prohibited MySubClass(const MySubClass&); // prohibited MySubClass & operator (const MySubClass&); // prohibited public : MySubClass(int x); }; class MyClass { MyClass(int x) : m_x(new SubClass(x)) {} ~MyClass() { delete m_x; } private : MySubClass * m_x; }; typedef multimap<Type, MyClass> my_multimap; typedef pair<Type, MyClass> my_pair; I'm trying to do the following : my_multimap my_map; my_map.insert(my_pair(One, MyClass(5))); And I'm getting an unhandled exception result, the app is trying to read 0xfeeefeee etc. What's going on? How can I fix this? Please note that this is a simplified case of what I'm dealing with;
MyClass has no copy constructor defined. However, std::pair will need to make use of the copy constructor for MyClass. Presumably it is using MyClass's default copy constructor, which will give copy constructed objects copies of the pointer m_x. And when they get destroyed, you'll be facing multiple deletions.
1,519,743
1,538,178
VC++ compiler for Qt Creator
I want to use the VC++ toolset to build programs for XP and Vista, but I do not want to buy the IDE, because I want to use Qt Creator. I would download the Windows SDK and the Windows Debugging Tools, but I'm not sure if this includes everything that I need (i.e: compiler, linker, nmake, debuggers). Has anyone used this approach? How did it go? Note: I know about VC++ Express, but that version of the compiler has certain features disabled AFAIK. Later edit: I want to know if I can use the SDK + Debugtools before I download 2GB of data. Personal experiences are highly appreciated. MSDN links are not. :)
I am now using the CDB + WinSDK approach and it works. The SDK includes everything that is needed for building C++ code (make, CRT headers, STL, etc); Qt sees it a MSVC 9. The Debugging tools for Windows kit includes CDB, but make sure that you're using the latest version, it didn't work for me with older ones. I managed to avoid compiling Qt by downloading the developpez.com binaries (thanks guys!). In conclusion: Windows Xp/Vista SDK + Debugger Tools For Windows + Qt Creator + Qt binaries from developpez.com can be used as an alternative to the Qt MinGW SDK.
1,519,772
1,519,803
What is the best solution to replace a new memory allocator in an existing code?
During the last few days I've gained some information about memory allocators other than the standard malloc(). There are some implementations that seem to be much better than malloc() for applications with many threads. For example it seems that tcmalloc and ptmalloc have better performance. I have a C++ application that uses both malloc and new operators in many places. I thought replacing them with something like ptmalloc may improve its performance. But I wonder how does the new operator act when used in C++ application that runs on Linux? Does it use the standard behavior of malloc or something else? What is the best way to replace the new memory allocator with the old one in the code? Is there any way to override the behavior or new and malloc or do I need to replace all the calls to them one by one?
From the TCMalloc documentation: To use TCmalloc, just link tcmalloc into your application via the "-ltcmalloc" linker flag. You can use tcmalloc in applications you didn't compile yourself, by using LD_PRELOAD: $ LD_PRELOAD="/usr/lib/libtcmalloc.so" ptmalloc seems to be similar (but if you're on Linux, you're likely already using it because it's part of the GNU C library). I would expect operator new to call malloc, but you can easily check for yourself by setting a breakpoint on malloc, then calling new. If your new doesn't call malloc, you can redefine it so that it does.
1,519,792
1,519,815
OUT OF MEMORY only when virtual limit is hit?
As I know in win32 every program receives say 4GB of virtual memory. Memory manager is responsible for offloading chunks of memory from physical memory to disk. Does it imply that malloc or any other memory allocation API will throw OUT_OF_MEMORY exception only when virtual limit is hit? I mean is it possible for malloc to fail even if program is far from its virtual size limit e.g. none of physical memory can be offloaded to disk. Assume disk have unlimited capacity and no specific limitation is set.
Yes, it's possible. Remember that memory can be fragmented and that malloc won't be able to find a sufficiently large chunk to serve the size you requested. This can easily be way before you hit your 4 GiB limit.
1,519,885
1,519,915
Defining own main functions arguments argc and argv
i want to create an object of type QApplication which needs the main functions arguments argc and argv as an input: QApplication app(argc, argv); Since i am within a user defined function without access to the main function i want to define this arguments on my own. I have tried several approaches but i cannot get the type conversion right. My last approach did not work either: int argc = 1; char **argv; char arguments[1][12] = {{"cgalExample"}}; argv = arguments; Thanks for any hint.
Quick and dirty, but working for QApplication: char *argv[] = {"program name", "arg1", "arg2", NULL}; int argc = sizeof(argv) / sizeof(char*) - 1; For a more complete and C standard conforming solution see D.Shawley's answer. Why your solution doesn't work is simple: array[i][j] results in a i*j matrix. But what you actually want is an array with pointers to strings in it.
1,520,001
1,523,297
How to get this getnameinfo code working
i am getting the error ai_family not supported in call to getnameinfo. 1 #include <iostream> 2 #include <sys/types.h> 3 #include <unistd.h> 4 #include <sys/socket.h> 5 #include <netdb.h> 6 #include <arpa/inet.h> 7 #include <iomanip> 8 extern "C" { 9 #include "../../pg/include/errhnd.h" 10 } 11 12 using namespace std; 13 14 15 int main(int argc, char** argv) 16 { 17 if (argc != 2) 18 err_quit("Usage: %s <ip address>", argv[0]); 19 20 struct sockaddr_in sa; 21 if (inet_pton(AF_INET, argv[1], &sa) <= 0) 22 err_sys("inet_pton error"); 23 24 char hostname[1000], servname[1000]; 25 26 cout << hex << (unsigned int)sa.sin_addr.s_addr << endl; 27 28 sa.sin_port = htons(80); 29 30 int x; 31 if ((x=getnameinfo((struct sockaddr*)&(sa.sin_addr), 32 16, hostname, 1000, servname, 1000, NI_NAMEREQD)) != 0) { 33 err_ret("getnameinfo error"); 34 cout << gai_strerror(x) << endl; 35 } 36 37 cout << hostname << " " << servname << endl; 38 39 return 0; 40 }
Your problem is with the call to inet_pton. When AF_INET is the address family passed, the dst pointer must be a pointer to a struct in_addr, not a struct sockaddr_in. Change line 21 to: if (inet_pton(AF_INET, argv[1], &sa.sin_addr) <= 0) Insert a line at line 23: sa.sin_family = AF_INET; Change lines 31-32 to: if ((x=getnameinfo((struct sockaddr*)&sa, sizeof sa, hostname, sizeof hostname, servname, sizeof servname, NI_NAMEREQD)) != 0) { then it should work.
1,520,018
1,520,044
C++ DAL - Return Reference or Populate Passed In Reference
[EDIT 1 - added third pointer syntax (Thanks Alex)] Which method would you prefer for a DAL and why out of: Car& DAL::loadCar(int id) {} bool DAL::loadCar(int id, Car& car) {} Car* DAL::loadCar(int id) {} If unable to find the car first method returns null, second method returns false. The second method would create a Car object on the heap and populate with data queried from the database. Presumably (my C++ is very rusty) that would mean code along the lines of: Car& DAL::loadCar(int id) { Car *carPtr = new Car(); Car &car= *carPtr; car.setModel(/* value from database */); car.setEngineSize(/* value from database */); // etc return car; } Thanks
The second is definitely preferable. You are returning a reference to an object that has been new'd. For an end user using the software it is not obvious that the returned object would require deleting. PLUS if the user does something like this Car myCar = dal.loadCar( id ); The pointer would get lost. Your second method therefore puts the control of memory on the caller and stops any weird mistakes from occurring. Edit: Return by reference is sensible but only when the parent, ie DAL, class has control over the lifetime of the reference. ie if the DAL class had a vector of Car objects in it then returning a reference would be a perfectly sensible thing to do. Edit2: I'd still prefer the second set up. The 3rd is far better than the first but you end up making the caller assume that the object is initialised. You could also provide Car DAL::loadCar(int id); And hope accept the stack copy. Also don't forget that you can create a kind of null car object so that you return an object that is "valid"ish but returns you no useful information in all the fields (and thus is obviously initialised to rubbish data). This is the Null Object Pattern.
1,520,022
1,520,088
how to write a text editor in c++
I learned c++ on and off for several times but never write a real apps using it . long time I've been thinking that writing a text editor will be something very interesting , now I am looking for a simple but decent text editor written in c or c++ from which I can get inspiration and learn how to write a text editor by myself. Could you guys recommend a "simple but decent" text editor written in c or c++ to me ?
Well what you want to see sounds more like a tutorial than an actual application (I think applications like Notepad++ will be a lot to dive into in the beginning). Since you don't mention any environment you want to program in, you could check out the QT Text Editor Demo. QT is a cross platform GUI Toolkit so you are not bound to a specific operating system but probably harder to setup then a Visual Studio environment in Windows. For Windows only you might want to think about digging more into the .NET platform (e.g. C#) as suggested in this question. It doesn't help learning C++ but it makes GUI development a hell of a lot easier.
1,520,192
1,520,260
C++ version of isnormal()
Is there a C++ version of the isnormal, isnan and so C functions? I know I can use the C functions from C++, but I'm always interested to know if there are some C++-only alternatives.
Not as far as I know. Doesn't look like there's one in the STL. Since that's such a simple function I would guess they didn't want to take the time to replace it. The old C version works fine. I would say just continue to use the C isnormal().
1,520,466
1,520,533
When to use run-time type information?
If I have various subclasses of something, and an algorithm which operates on instances of those subclasses, and if the behaviour of the algorithm varies slightly depending on what particular subclass an instance is, then the most usual object-oriented way to do this is using virtual methods. For example if the subclasses are DOM nodes, and if the algorithm is to insert a child node, that algorithm differs depending on whether the parent node is a DOM element (which can have children) or DOM text (which can't): and so the insertChildren method may be virtual (or abstract) in the DomNode base class, and implemented differently in each of the DomElement and DomText subclasses. Another possibility is give the instances a common property, whose value can be read: for example the algorithm might read the nodeType property of the DomNode base class; or for another example, you might have different types (subclasses) of network packet, which share a common packet header, and you can read the packet header to see what type of packet it is. I haven't used run-time-type information much, including: The is and as keywords in C# Downcasting The Object.GetType method in dot net The typeid operator in C++ When I'm adding a new algorithm which depends on the type of subclass, I tend instead to add a new virtual method to the class hierarchy. My question is, when is it appropriate to use run-time-type information, instead of virtual functions?
When there's no other way around. Virtual methods are always preferred but sometimes they just can't be used. There's couple of reasons why this could happen but most common one is that you don't have source code of classes you want to work with or you can't change them. This often happens when you work with legacy system or with closed source commercial library. In .NET it might also happens that you have to load new assemblies on the fly, like plugins and you generally have no base classes but have to use something like duck typing.
1,520,467
1,520,771
Where do I use BackTrace calls on the Mac
I want to get a BackTrace from my crashing C++ Mac application however I am new to the Mac and am not sure how best to go about it. I found a question on stackoverflow that details its usage: getting the current stack trace on mac os x However my problem is that I do not see where the code is meant to live? Does it go in the main.cpp? Does it live in the catch part of a try catch block? I could do with some full code examples but am having trouble finding them.
The code referred to in the other question needs to go where it will get executed after the crash. Depending on what is happening that could either be in a catch block if an exception is getting thrown, or in a signal handler if the program is crashing because of, for example, a seg fault or bus error. Here is an example for catching signals. It would go in main(). static void CatchSignal(int num) { // code to execute when signal is caught } void InstallSignalHandler(const int which[15]) { for (int i = 1; i < 15; i++) if (which[i] != 0 && which[i] != SIGABRT) signal(which[i],CatchSignal); }