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: S...
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 o...
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. T...
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...
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, ...
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...
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 ...
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 li...
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 f...
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 vis...
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 gener...
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 != sta...
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...
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 co...
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_bAu...
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 bDisableIfNoHndle...
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 sop...
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 no...
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...
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? ex...
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.si...
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 a...
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 specia...
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_iterat...
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 le...
((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 'doubl...
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 "#defin...
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 th...
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...
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-poi...
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...
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 b...
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, becau...
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 c...
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...
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 e...
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 declar...
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 existen...
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 p...
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 linea...
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 s...
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 witho...
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 licens...
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...
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 new...
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...
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 ...
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 f...
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...
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"); Distin...
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...
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. b2BodyD...
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 i...
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)...
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. ...
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) //...
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::vect...
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...
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...
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 com...
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 strin...
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 an...
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 ...
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...
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 fun...
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...
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 ...
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, techni...
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 ...
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 res...
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(hea...
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...
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 ca...
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 whi...
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> { ...
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....
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 i...
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 :...
**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...
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...
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> #inc...
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 ne...
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...
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 al...
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()...
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 lead...
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 ...
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 t...
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 c...
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! { ...
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 fu...
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 WSVER...
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. Cla...
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 dr...
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 ther...
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 s...
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" ...
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); ob...
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,...
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; } privat...
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 ...
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 ...
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 th...
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 r...
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 <...
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 : pub...
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() { ...
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...
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 ty...
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() { del...
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 thi...
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 man...
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 t...
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...
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 mal...
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...
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 a...
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 ...
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 (...
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...
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 ...
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...
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 n...
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 subclas...
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 sys...
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...
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 ex...