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
3,060,295
3,060,327
"Socket operation on non-socket" error due to strange syntax
I ran across the error Socket operation on non-socket in some of my networking code when calling connect and spent a lot of time trying to figure out what was causing it. I finally figured out that the following line of code was causing the problem: if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol...
Actually, you don't get any warning because of the double parenthesis (. Try to remove one pair, and you'll get the warning back. #include <iostream> int foo() { return 2; } int main(int /*argc*/, char** /*argv*/) { int l; if ((l = foo() < 3)) // Won't generate warning under gcc { } if (l = ...
3,060,348
3,060,907
what are the devices will be listed
please let me know what are the devices wil be listed using the below code guid = GUID_DEVINTERFACE_VOLUME; // Get device Information handle for Volume interface hDevInfo = SetupDiGetClassDevs( &guid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT ); Thank you
All devices that are present in the system that have enabled an interface from the storage volume device interface class. You can find more information here
3,060,417
3,060,462
Compile C++ program on Mac to run on Linux
Possible Duplicate: How to cross compile from Mac OS X to Linux x86? I have an application that I wrote in C++/SDL, using FMOD library. The app is portable and compiles without any code change on Mac and on Linux. But one annoyance is that when I want to ship Linux version, I have to run my Linux box, copy the sourc...
A quick google for cross-compiling for Linux on OSX revealed this page. Actually, this has been asked before in How to cross compile from Mac OS X to Linux x86?.
3,060,440
3,060,594
Avoid Resource Conflict
I have a MFC exe, trying to dynamic load a MFC dll. // This is code in MFC exe HINSTANCE h = AfxLoadLibrary(_T("DLL.dll")); typedef void(*FUN)(); FUN fun = (FUN)GetProcAddress(h, "loveme"); FreeLibrary(h); Both MFC exe and MFC dll, are having their own resource file. However, I realize that, if MFC exe and MFC dll are...
You will need to keep track handle to yourself, which will be passed in during dllmain. HINSTANCE hDLLInstance = 0; extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { hDLLInstance = hInstance; ... } then when you want to refer to local resources (ie. LoadString), pass th...
3,060,545
3,060,625
can function return 0 as reference
I have this snippet of the code Account& Company::findAccount(int id){ for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){ if(i->nID == id){ return *i; } } return 0; } Is this right way to return 0 if I didn...
Why don't you use a standard algorithm like std::find_if. Edit: Explanation of find_if. Here is the reference for find_if algorithm. http://cplusplus.com/reference/algorithm/find_if/ bool isEqual(int id1, int id2) { return id1 == id2; } void foo() { std::list<Account> accountList; // Fill this list here. ...
3,060,572
3,060,885
c++ protected pointer member to the same class and access privileges
Example code is included at the bottom of the message. I'm puzzled about the protected access specifier in a class. I have define a class node which has a protected string member name string name; and a vector of node pointers vector args; Before I thought that a member function of node could not do args[0]->name but a...
The compiler will allow that an object A accesses private/protected members of an object B if A and B have the same static type. I will try to make this clear with an example: class Base { protected: int a; }; class Derived : public Base { public: void foo(Base& b, Derived& d) { ...
3,060,577
3,090,854
Can the dirtiness of pages of a mmap be found from userspace?
Can dirtiness of pages of a (non-shared) mmap be accessed from userspace under linux 2.6.30+? Platform-specific hacks and kludges welcome. Ideally, I'm looking for an array of bits, one per page (4kB?) of the mmap'ed region, which are set if that page has been written to since the region was mmap'ed. (I am aware, that...
See /proc/*/pagemap and /proc/kpageflags interfaces. First tells you PFN for an address, second tells you dirty bit given PFN. See fs/proc/task_mmu.c , Documentation/vm/pagemap.txt, Documentation/vm/page-types.c .
3,060,670
3,062,760
Is there any API to get path "C:\Documents and Settings" in windows?
Is there any API to get path : "C:\Documents and Settings" in windows in c++? not: C:\Documents and Settings\brianfu\My Documents. Many Thanks! Thanks for luke's solution: GetProfilesDirectory it works!
GetProfilesDirectory
3,060,671
3,060,692
Does this code follow the definition of recursion?
I have a piece of code which I am doubting it as a implementation of recursion by its definition. My understanding is that the code must call itself, the exact same function. I also question whether writing the code this way adds additional overhead which can be seen with the use of recursion. What are your thoughts? c...
Yes, since you have certain functions calling themselves. By definition that is direct recursion. You could also have indirect recursion if you had function A() calling function B(), function B() in turn (directly or indirectly) calling function A() again.
3,060,688
3,060,701
Prohibiting copy construction and copy assignment in C++
To prohibit copy construction and copy assignment, I've seen the boost noncopyable class and in the Google style guide the DISALLOW_COPY_AND_ASSIGN macro. Is there any reason to prefer one of the techniques over the other, or any subtle differences one should be aware of?
I prefer boost noncopyable over the macro because it's not a macro and it is easier (IMO) to use. In real code, i'm using neither of them and write the two declarations needed myself. A subtle difference you might be interested in, though, is that using that macro or your own declarations will not give a compiler err...
3,060,730
3,060,745
C++: Avoid .cpp files with only an empty (de)constructor
When I have a header file like this: #ifndef GAMEVIEW_H_ #define GAMEVIEW_H_ #include <SDL/SDL.h> class GameView { public: GameView(); virtual ~GameView(); virtual void Update() = 0; virtual void Render(SDL_Surface* buffer) = 0; }; #endif /* GAMEVIEW_H_ */ I need to create a .cpp file like this: #include "Game...
You can define your constructor and destructor (this is the proper term, use this instead of deconstructor) inline: class GameView { public: GameView() {} virtual ~GameView() {} virtual void Update() = 0; virtual void Render(SDL_Surface* buffer) = 0; };
3,060,776
3,060,818
Compiler doesn't find methods from base class
I am having a problem with my virtual methods in a derived class. Here are my (simplified) C++ classes. class Base virtual method accept( MyVisitor1* v ) { /*implementation is here*/ }; virtual method accept( MyVisitor2* v ) { /*implementation is here*/ }; virtual method accept( MyVisitor3* v ) { /*implementat...
The accept member of DerivedClass hides any members of the base class with the same name, even if they have different signatures. To include them, add the following to the definition of DerivedClass: using Base::accept; (I'm assuming that DerivedClass does derive from Base; your snippet doesn't explicitly say that).
3,060,828
3,060,865
Is the order of declarations within a class important?
Can somebody please explain the order of private and public in a class. Is it important or not? For example: class Account{ public: Account(string firstName, string lastName, int id); void printAccount(); private: string strLastName; string strFirstName; }; Will it be the same as: class Accoun...
It's important for the visibility of class members class Account{ public: Account(string firstName, string lastName, int id); void printAccount(); Foo makeFoo(); // invalid! Foo not declared yet typedef Foo foo_type; // invalid! Foo not declared yet private: string strLastName; string str...
3,060,911
3,060,939
An exception to the "only one implementation" rule?
While I was reading the accepted answer of this question, I had the following question: Typically, methods are defined in header files (.hpp or whatever), and implementation in source files (.cpp or whatever). One of the main reasons it is bad practice to ever include a "source file" (#include <source_file.cpp>) is tha...
Inline functions are exceptions to the "one definition rule": you are allowed to have identical implementations of them in more than one compilation unit. Functions are inline if they are declared inline or implemented inside a class definition.
3,060,946
3,060,998
Implementing a State Machine in C++ HOW?
I'm new to C++. How can I implement a State Machine in C++ ? I'm getting only the messages and should know the next state. What is the proper structure I need to use ? Thanks, Igal
typedef std::pair<State,Message> StateMessagePair; typedef std::map<StateMessagePair,State> StateDiagram; StateDiagram sd; // add logic to diagram ... State currentState = getInitialState(); ... // process message Message m = getMessage(); StateDiagram::iterator it=sd.find(std::make_pair(currentState,m))); if (it==sd.e...
3,061,135
3,061,170
Can we write an EOF character ourselves?
Most of the languages like C++ when writing into a file, put an EOF character even if we miss to write statements like : filestream.close However is there any way, we can put the EOF character according to our requirement, in C++, for an instance. Or any other method we may use apart from using the functions provided i...
There is no EOF character. EOF by definition "is unequal to any valid character code". Often it is -1. It is not written into the file at any point. There is a historical EOF character value (CTRL+Z) in DOS, but it is obsolete these days. To answer the follow-up question of Apoorv: The OS never uses the file data to de...
3,061,203
3,061,272
Implicit conversion while using += operator?
Conside the following code: int main() { signed char a = 10; a += a; // Line 5 a = a + a; return 0; } I am getting this warning at Line 5: d:\codes\operator cast\operator cast\test.cpp(5) : warning C4244: '+=' : conversion from 'int' to 'signed char', possible loss of data Does this mean th...
What you are seeing is the result of integral promotion. Integral promotion is applied to both arguments to most binary expressions involving integer types. This means that anything of integer type that is narrower than an int is promoted to an int (or possibly unsigned int) before the operation is performed. This mean...
3,061,247
3,061,350
Initialization of a vector of vectors?
Is there a way to initialize a vector of vectors in the same ,quick, manner as you initialize a matrix? typedef int type; type matrix[2][2]= { {1,0},{0,1} }; vector<vector<type> > vectorMatrix; //???
For the single vector you can use following: typedef int type; type elements[] = {0,1,2,3,4,5,6,7,8,9}; vector<int> vec(elements, elements + sizeof(elements) / sizeof(type) ); Based on that you could use following: type matrix[2][2]= { {1,0},{0,1} }; vector<int> row_0_vec(matrix[0], matrix[0] + sizeof(matrix[0]) /...
3,061,324
3,061,437
returning of the iterator in C++
can somebody explain I can I return list iterator? list<Account>::iterator Company::findAccount(int id){ for(list<Account>::iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){ if(i->getID() == id){ return i; } } return 0; } and also is it good practice, to retu...
In your case returning an iterator exposes internals of the class, and that is almost always a bad thing. As @Paul said in his answer, some STL-algorithms return iterators. However, they return iterators on the input-collection. From the name of your method I guess it would be the best thing to return an object or a co...
3,061,341
3,061,494
error in c, but not in c++
const int t=5; char buf[t+5]; When I compile this gives error in C but not in C++!! Can anybody please explain me the reason? Note: I know the const defaults to internal linkage in 'C++', where as in 'C' it defaults to external linkage. Does it has any relation to the above case??
As others explained, C is kept more simple than C++ and doesn't allow const variables to appear in integer constant expressions. But in both C89 and C++ declared arrays must have compile-time constant sizes. You can use enumerations for this enum { BufSize = 5 }; char buf[BufSize + 5]; It doesn't have to do with i...
3,061,528
3,066,996
Is there a way to have multiple "name=value" lines in the INI file using boost::program_options::parse_config_file?
I want to be able to specify multiple name=value lines in the INI file using boost::program_options. Something like [list.names] name=value name=value2 name=value3 Is there a way to achieve this with boost::program_options? I get a multiple occurrences error if I try it If not, what other libraries are available?
Specify the value of the field as std::vector<value_type> in the options_description: namespace po = boost::program_options; po::options_description desc; desc.add_options() ("list.names.name", po::value< std::vector<std::string> >(), "A collection of string values"); po::variables_map vm; std::ifstream ini_file(...
3,061,582
3,061,610
Include all files in a directory?
How can one achieve what the following code is trying to do? #include "dir/*"
In Bash: HEADER=all_headers.h echo "#ifndef __ALL_HEADERS__" > $HEADER echo "#define __ALL_HEADERS__" >> $HEADER for file in dir/*.h do echo "#include <$file>" >> $HEADER done echo "#endif" >> $HEADER
3,061,698
3,061,717
auto_inline - inadequate documentation
I want to disable inlining for a particular function. What the compiler does for everything else should be as specified in the project properties. I found a page on a forum which suggested the following: #pragma auto_inline(off) void func() { } #pragma auto_inline() The author suggested that calling auto_inline() with...
__declspec(noinline) void func() { }
3,061,721
3,062,065
Concatenate boost::dynamic_bitset or std::bitset
what is the best way to concatenate 2 bitsets? For example i've got boost::dynamic_bitset<> test1( std::string("1111") ); boost::dynamic_bitset<> test2( std::string("00") ); they should be concatenated into a thrid Bitset test3 which then holds 111100 Solutions should use boost::dynamic_bitset. If the solution works...
For the standard bitset, something like: #include <bitset> #include <string> #include <iostream> using namespace std; template <size_t N1, size_t N2 > bitset <N1 + N2> concat( const bitset <N1> & b1, const bitset <N2> & b2 ) { string s1 = b1.to_string(); string s2 = b2.to_string(); return bitset <N1 + N2>(...
3,061,821
3,061,882
c++ polymorphism and other function question
i have got this code: class father{ public: virtual void f() { cout<<1;} }; class son:public father{ public: void f() {cout<<2;} }; void test (father x){x.f();} int main(){ son s; test(s); } the question says: the output is '1', what is the rule about polymorphism that the programmer forgot and how...
When you pass the son object to the test function by value, it will be converted to a father object because test takes a father, not a son. If you want to accept instances of subclass without conversion, you need to accept the argument by reference or pointer. So if you change the signature of test to void test (father...
3,061,910
3,061,919
How to clean up a vector/map properly?
If I have a vector<string*> *vect or a map<pair<string*, int*>, string*> *map, how to clean up everything (including all object the vector/map contains)? (Everything (vector, map, contents, string, ints) is allocated with new) Is this enough: delete vect; delete map;
No, you must iterate through the vector/ map, remove and delete its items one by one (which, as @SB pointed out, may require disposing of their members recursively). (You could get away by simply deleting the items, if you are absolutely sure no one will access the vector elements anymore before the vector gets deleted...
3,061,979
3,062,002
operator << overload c++
how can i overload "<<" operator (for cout) so i could do "cout" to a class k
The canonical implementation of the output operator for any type T is this: std::ostream& operator<<(std::ostream& os, const T& obj) { os << obj.get_data1() << get_data2(); return os; } Note that output stream operators commonly are not member functions. (That's because for binary operators to be member functions...
3,062,162
3,062,279
how to emulate thread local storage at user space in C++?
I am working on a mobile platform over Nucleus RTOS. It uses Nucleus Threading system but it doesn't have support for explicit thread local storage i.e, TlsAlloc, TlsSetValue, TlsGetValue, TlsFree APIs. The platform doesn't have user space pthreads as well. I found that __thread storage modifier is present in most of t...
I alwasy used the ACE library when needing thread local storage. I don't know if it is available for your system. If so check out class ACE_TSS. For the __thread keyword, there is an wikipedia page, where it is described.
3,062,258
3,062,316
vector holding read-only matrices?
I want to use a vector to hold read-only integer-matrices of the size 5x5 vector<const int[5][5]> startingPieces; But this declaration causes a bunch of weird errors I've never ever seen before. error C2535: 'const int (*std::allocator<_Ty>::address(const int (&)[5][5]) const)[5][5]' : member function already defined ...
What you should do here is create your own matrix class that stores the 5x5 array of data and then create your vector with that.
3,062,277
3,062,368
Sample Code with Examples for the C++ Google Style Guide?
Are there any good places to get examples for the C++ Google Style Guide?
Google open sources a number of projects, most of which comply with their style guides: protocol buffers re2 - pcre regular expressions perf tools - multithreaded performance analysis tools gflags - command line flags Search Google code for google projects, and you'll find a lot!
3,062,331
3,062,367
C++ template restrictions
I wondering is there any way to set restrictions on template class? Specify that every type substituted in template must have specific ancestor (realize some interface). template < class B > //and every B must be a child of abstract C class A { public: B * obj; int f() { return B::x + this->obj->f(); ...
You can use BOOST_STATIC_ASSERT or a similar library to assert your restrictions on the template parameter. For example: #include <limits> #include <boost/static_assert.hpp> template <class UnsignedInt> class myclass { private: BOOST_STATIC_ASSERT((std::numeric_limits<UnsignedInt>::digits >= 16) ...
3,062,360
3,062,444
Const Member function Vs Const Friend Function
How this code modifies a value in a const function: #include<iostream> using namespace std; class Y; class X{ public: void access(Y &y) const; }; class Y{ int d; public: friend void X::access(Y &y) const; Y(){d=0;} }; void X::access(Y &y) const { cout<<"Y is "<<y.d<<endl; y.d=1; cout...
Because inside a const function, only *this is const, not the parameters passed to the function or anything else.
3,062,518
3,062,822
What kind of good approaches do C++ programmers use for storing error messages?
Say I have a huge amount of code and have different kinds of error messages. For these, I want to have a separate place where I store error codes and error messages. For example, for an error that occured because the program could not open a file I store: F001 "Can not open a file." "The same error message in anothe...
I would use XML like this: <languageList> <language short="de" long="Deutsch" default="true" /> <language short="en" long="English" /> </languageList> <string alias="couldNotOpenFileError" de="Konnte Datei nicht öffnen" en="Could not open file" /> <string alias="couldNotWriteFileError" de="Konnt...
3,062,616
3,062,736
an error within context
can somebody please explain my mistake, I have this class: class Account { private: string strLastName; string strFirstName; int nID; int nLines; double lastBill; public: Account(string firstName, string lastName, int id); friend string printAccount(string...
I imagine the full error has something to do with "These members are private within context" and some line numbers. The issue is that i->strFirstName is private from the perspective of the reportAccounts() function. A better solution may be: class Account{ private: string strLastName; string s...
3,062,647
3,062,899
How to get every virtual function index just as the compiler does?
Is there some plugin or tool which can read a .h file (or simply modify Intellisense itself) and spit out every function and it's virtual function table index? There's a pattern which I have yet to figure out having to do with polymorphism, and it gets 5x harder when you start to have 5 classes or more deriving from ea...
Use the hidden Microsoft C/C++ compiler option "/d1 reportAllClassLayout". This will print out the memory layout and vtables of all your classes.
3,062,734
3,063,148
Possible to distribute an MPI (C++) program accross the internet rather than within a LAN cluster?
I've written some MPI code which works flawlessly on large clusters. Each node in the cluster has the same cpu architecture and has access to a networked (i.e. 'common') file system (so that each node can excecute the actual binary). But consider this scenario: I have a machine in my office with a dual core processor ...
Its possible to do this. Most MPI implementations allow you to specify the location of the binary to be run on different machines. Alternatively, make sure that it is in your path on both machines. Since both machines have the same byte order, that shouldn't be a problem. You will have to make sure that any input d...
3,062,746
3,062,783
Special simple random number generator
How to create a function, which on every call generates a random integer number? This number must be most random as possible (according to uniform distribution). It is only allowed to use one static variable and at most 3 elementary steps, where each step consists of only one basic arithmetic operation of arity 1 or 2....
Linear congruential generators are one of the oldest and simplest methods: int seed = 123456789; int rand() { seed = (a * seed + c) % m; return seed; } Only a few instruction with basic arithmetic operations, that's all you need. Mind that this algorithm works fine only if a, c and m are chosen in a particular wa...
3,062,803
3,073,354
How do I cleanly reconnect a boost::socket following a disconnect?
My client application uses a boost::asio::ip::tcp::socket to connect to a remote server. If the app loses connection to this server (e.g. due to the server crashing or being shutdown) I would like it to attempt a re-connect at regular intervals until it succeeds. What do I need to do on the client-side to cleanly handl...
You need to create a new boost::asio::ip::tcp::socket each time you reconnect. The easiest way to do this is probably to just allocate the socket on the heap using a boost::shared_ptr (you could probably also get away with scoped_ptr if your socket is entirely encapsulated within a class). E.g.: bool MyClient::myconn...
3,062,931
3,064,855
Does speed of an C/C++, Windows console application depend on whether the target is 32 or 64 bit?
Supposing that memory is not an issue does targeting a 64 bit OS make a C/C++ Windows console application run faster? Update: Prompted by a few comments/answers the application involves statistical algorithms (e.g., linear algebra, random number draws etc).
Replying mostly to the edit, not the original question: I've ported one application that's heavy on statistics and (especially) linear algebra to run as 64-bit code. For that code, the effort was minimal, and we got about a 3:1 improvement in speed. I suspect that the majority of the notion that there often won't be co...
3,062,987
3,063,187
Where can I find some in-depth DirectX 11 tutorials?
So far the only tutorials I've been able to find are on directx11tutorials.com, which are essentially inferred from the existing samples. Does anyone know where to find other tutorials, or better yet open source projects using DirectX 11? (Extra points for project code using DirectX 11 :) )
I think there are still no DX11 tutorials / books. If you want to study DirectX in-depth, you could grab some DX10 book and also examine DX11 SDK and MSDN. There is nothing really new in DirectX 11 (in application architecture / code building principles), so you could examine new API features and (if you're actually p...
3,063,110
8,556,254
Get the current operating system during runtime in C++
I need to figure out the operating system my program is running on during runtime. I'm using Qt 4.6.2, MinGW and Eclipse with CDT. My program shall run a command-line QProcess on Windows or Linux. Now I need a kind of switch to run the different code depending on the operating system.
Actually the Operating System is defined by the Q_OS_... macros. Just saying. The Q_WS_... are windowing system. Not exactly the same. (I'm just reading what the author of the question wrote.... "operating system".) These declarations are found in the qglobal.h file. Use Q_OS_x with x being one of: DARWIN - Darwin ...
3,063,341
3,063,401
Can a destructor be recursive?
Is this program well-defined, and if not, why exactly? #include <iostream> #include <new> struct X { int cnt; X (int i) : cnt(i) {} ~X() { std::cout << "destructor called, cnt=" << cnt << std::endl; if ( cnt-- > 0 ) this->X::~X(); // explicit recursive call to dtor ...
The answer is no, because of the definition of "lifetime" in §3.8/1: The lifetime of an object of type T ends when: — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or — the storage which the object occupies is reused or released. As soon as the destructor is called (the first ...
3,063,514
3,063,552
What does it mean to pass a &variable to a function? E.g., string& insert ( size_t pos1, const string& str );
I understand passing a pointer, and returning a pointer: char * strcat ( char * destination, const char * source ); You're passing a variable that contains the address to a char; returning the same. But what does it mean to pass something using the reference operator? Or to return it? string& insert ( size_t pos1, con...
Simply said, a reference is a pointer without telling you it's a pointer. If you would write the following in plain C: void getpi (float *f) { *f = 3.14; } float v; getpi(&v); You can write the following in C++ using references: void getpi (float &f) { f = 3.14; } float v; getpi(v); It has the additional advantage ...
3,063,534
3,063,881
Can I pass a pointer to a superclass, but create a copy of the child?
I have a function that takes a pointer to a superclass and performs operations on it. However, at some point, the function must make a deep copy of the inputted object. Is there any way I can perform such a copy? It occurred to me to make the function a template function and simply have the user pass the type, but I h...
SpaceCowboy proposes the idiomatic clone method, but overlooked 3 crucial details: class Super { public: virtual Super* clone() const { return new Super(*this); } }; class Child: public Super { public: virtual Child* clone() const { return new Child(*this); } }; clone is a const method clone returns a pointer to...
3,063,611
3,063,658
Just how much do I want to make virtual?
I am writing an abstract superclass where literally every method is going to be overridden. There is some default functionality I could implement, but most of the time it's enough to leave the implementation to the subclass writer. Since just about every method is going to be overwritten, how much should I make virtua...
Virtual function calls are slower than non-virtual ones, but if you need runtime polymorphism, there's no alternative. Virtual function calls have a roughly constant overhead regardless of how many you have, so there's little disadvantage. You can see the design of many professional classes- like IDirect3D9Device- have...
3,063,690
3,063,938
I have a bunch of template parameters that I want to hide from my users. How can I do this?
I have a superclass which is defined in terms of a few internal types it uses. Subclassing is performed as so: template <class InternalType1, class InternalType2> class Super { ... } class Sub : Super <interalTypeClass1, interalTypeClass2> { ... } But when I want to write a function that takes a pointer to ...
template <class TInternal1, TInternal2> class Super { private: /*...*/ public: typedef TInternal1 internal_type_1; typedef TInternal2 internal_type_2; /*...*/ }; typedef Super<int, char> IntCharSuper; typedef Super<bool, char> BoolCharSuper; class Sub1 : IntCharSuper {/*.....
3,063,800
3,063,853
I can't put a string in a switch nor an array in a class
Okay, im making a pretty big file in my opinion, so i wanted to separate it into several files for cleaner code. so i have my main .cpp file and two header files holding my classes. well the header files dont hold strings, it aboslutely wont budge. i call the library in both my .cpp file and even tried it in my header...
"string" does not name a type Add #include <string> at the top of your header file, since it is used in the header file, it must be included first. Since string is defined in the std namespace, you should declare it with std::string name;. In the cpp file, you can shortcut with using namespace std;, but it might be ...
3,063,834
3,064,055
Function returning MYSQL_ROW
I'm working on a system using lots of MySQL queries and I'm running into some memory problems I'm pretty sure have to do with me not handling pointers right... Basically, I've got something like this: MYSQL_ROW function1() { string query="SELECT * FROM table limit 1;"; MYSQL_ROW return_row; mysql_init(&connec...
Update: I misunderstood how mysql results are used. It looks like the row pointer array points to the results array which you free in function1() and then use it in function2() after it has been returned to the heap. What you need to do is copy return_row[2] to a persistent string before freeing the results. Then pa...
3,063,973
3,064,026
Generating code at compile-time using scripts
I would ideally like to be able to add (very repetitive) C/C++ code to my actual code, but at compile time, code which would come from say, the stdout of a python script, the same way one does with macros. For example, let's say I want to have functions that depend on the public attributes of a given class, being able ...
You do most likely need to tweak the Makefile a bit. It would be easy to write a (Python) script that reads each of your source files as an additional preprocessing step, replacing instances of generate_boring_functions (or any other script-macro) with the correct code, potentially just by invoking generate_boring_func...
3,063,987
3,064,039
need help with C++ using maps to keep track of words in a INPUT file
Let say i have a text file with today is today but tomorrow is today tomorrow then using maps how can i keep track of the words that are repeated? and on which line it repeats? so far i have each string in the file read in as a temp and it is stored in the following way: map<string,int> storage; int count = 1...
map stores a (key, value) pair with a unique key. Meaning that if you assign to the same key more than once, only the last value that you assigned will be stored. Sounds like what you want to do is instead of storing the line as the value, you want to store another map of lines->occurances. So you could make your ma...
3,064,052
3,064,412
C++ project type: unicode vs multi-byte; pros and cons
I'm wondering what the Stack Overflow community thinks when it comes to creating a project (thinking primarily c++ here) with a unicode or a multi-byte character set. Are there pros to going Unicode straight from the start, implying all your strings will be in wide format? Are there performance issues / larger memory ...
Two issues I'd comment on. First, you don't mention what platform you're targeting. Although recent Windows versions (Win2000, WinXP, Vista and Win7) support both Multibyte and Unicode versions of system calls using strings, the Unicode versions are faster (the multibyte versions are wrappers that convert to Unicode, c...
3,064,062
3,064,324
C# & C++, runtime error when call C++ dll from C#
I have written a C++ wrapper DLL for C# to call. The DLL was tested and worked fine with my C++ test program. now integrated with C#, I got runtime error and crashed. Cannot use debugger to see more details. The C++ side has only one method: #ifdef DLLWRAPPERWIN32_EXPORTS #define DLLWRAPPERWIN32_API __declspec(dllexpor...
There are a bunch of rules for marsheling with PInvoke. For reference Marsheling between managaed & unmanaged Focusing on the C# side first. If you knew a reasonable size of the message up front you could use StringBuilder type and define that size, something like. [DllImport("DLLWrapperWin32.dll")] public static exter...
3,064,237
3,064,262
C++: Maybe you know this pitfall?
I'm developing a game. I have a header GameSystem (just methods like the game loop, no class) with two variables: int mouseX and int mouseY. These are updated in my game loop. Now I want to access them from Game.cpp file (a class built by a header-file and the source-file). So, I #include "GameSystem.h" in Game.h. Afte...
In your GameSystem header, don't define those variables as: int mouseX; int mouseY; instead, you should declare them: extern int mouseX; extern int mouseY; Then in one of your .cpp files you define them: int mouseX; int mouseY; The problem with defining them in a header file is that the compiler will try to instanti...
3,064,509
3,064,568
Cast from Void* to TYPE* using C++ style cast: static_cast or reinterpret_cast
So if your converting from Void* to Type* or from Type* to Void* should you use: void func(void *p) { Params *params = static_cast<Params*>(p); } or void func(void *p) { Params *params = reinterpret_cast<Params*>(p); } To me static_cast seems the more correct but I've seen both used for the same purpose. Als...
You should use static_cast so that the pointer is correctly manipulated to point at the correct location. However, you should only do this if you used static cast to cast the pointer to void* in the first place. Otherwise you should reinterpret_cast to exactly the same type of the original pointer (no bases or such)....
3,064,559
3,064,579
How is vector implemented in C++
I am thinking of how I can implement std::vector from the ground up. How does it resize the vector? realloc only seems to work for plain old stucts, or am I wrong?
it is a simple templated class which wraps a native array. It does not use malloc/realloc. Instead, it uses the passed allocator (which by default is std::allocator). Resizing is done by allocating a new array and copy constructing each element in the new array from the old one (this way it is safe for non-POD objects)...
3,064,668
3,094,248
A good ORM to use with qt4 (c++) ? (Django like...)
Does anyone have a recommendation for an ORM for qt4 (c++)? (Like a Django ORM).
I would suggest you take a look at the QDjango ORM, it might be just what you are looking for. This C++ ORM only depends on Qt and builds upon Qt's Meta-Object System to provide introspection. On top of the basic create/update/delete operations at the model level, it provides a queryset template class (modeled after dj...
3,064,926
3,064,939
How to write log base(2) in c/c++
Is there any way to write log(base 2) function? The C language has 2 built in function -->> 1.log which is base e. 2.log10 base 10; But I need log function of base 2.How to calculate this.
Simple math:     log2 (x) = logy (x) / logy (2) where y can be anything, which for standard log functions is either 10 or e.
3,064,944
3,064,984
DLL Export C/C++ 6.00 function invoked by VB6
I have been attemptng to create a DLL with C/C++ that can be accessed by VB6, and that's right I get error "453 Can't find DLL entry point myFunctionName in myDllName.dll" upon calling the function from a VB6 app. After searching the Web, including this site, I see that I am not alone, and I have tried the various solu...
You are doing everything right as near as I can tell. Verify your assumptions by running Dumpbin.exe /exports on the DLL. That shows the actual name of the exported function, it has to match the Alias in the VB6 declaration. The only other failure mode I can think of is VB6 loading the wrong DLL. It has to be presen...
3,064,976
3,065,119
Why have pointer parameters?
Possible Duplicates: Why use pointers? Passing a modifiable parameter to c++ function Why would I want to have pointer parameters? The only reason I can see is for small functions to attempt to reduce confusion and a smaller memory footprint.
In Passing a modifiable parameter to c++ function I answered when to use a reference instead of a pointer. Conversely, prefer a pointer to a reference when any of the following are true: It can be null It can be changed (to point to something else) It must be deleted Some people also prefer a pointer when the thing t...
3,065,092
3,065,211
Check if a pointer points to allocated memory on the heap
I want to know if a pointer points to a piece of memory allocated with malloc/new. I realize that the answer for an arbitrary address is "No you can't" but I do think it is possible to override malloc/free and keep track of allocated memory ranges. Do you know a memory management library providing this specific tool? ...
There's no standard way to do this, but various malloc debugging tools may have a way of doing it. For example, if you use valgrind, you can use VALGRIND_CHECK_MEM_IS_ADDRESSABLE to check this and related things
3,065,109
3,073,077
Can Boost Program_options separate comma separated argument values
If my command line is: > prog --mylist=a,b,c Can Boost's program_options be setup to see three distinct argument values for the mylist argument? I have configured program_options as: namespace po = boost::program_options; po::options_description opts("blah") opts.add_options() ("mylist", std::vector<std::string>>...
You could register a custom validator for your option: namespace po = boost::program_options; struct mylist_option { // values specified with --mylist will be stored here vector<std::string> values; // Function which validates additional tokens from command line. static void validate(boost::any &...
3,065,154
3,087,312
Undefined reference to vtable
When building my C++ program, I'm getting the error message undefined reference to 'vtable... What is the cause of this problem? How do I fix it? It so happens that I'm getting the error for the following code (The class in question is CGameModule.) and I cannot for the life of me understand what the problem is. At...
So, I've figured out the issue and it was a combination of bad logic and not being totally familiar with the automake/autotools world. I was adding the correct files to my Makefile.am template, but I wasn't sure which step in our build process actually created the makefile itself. So, I was compiling with an old makefi...
3,065,200
3,065,510
Inheritence and usage of dynamic_cast
Suppose I have 3 classes as follows (as this is an example, it will not compile!): class Base { public: Base(){} virtual ~Base(){} virtual void DoSomething() = 0; virtual void DoSomethingElse() = 0; }; class Derived1 { public: Derived1(){} virtual ~Derived1(){} virtual void DoSomething(){ ... } ...
Using dynamic_cast is not bad practice per se. It's bad practice to use it inappropriately, i.e. where it's not really needed. It's also a bad practice to use it this way: (dynamic_cast<Derived1*>(b))->SpecialD1DoSomething(); Reason: dynamic_cast(b) may return NULL. When using dynamic_cast, you have to be extra car...
3,065,221
3,065,259
Moving from Java to C++ API's
There are some particular API's in Java that make it very good. However I would prefer C++ because of performance and "bleeding" edge support with OpenGL and OpenAL among the many libraries. Which API's are there that are similar to Java2D (I know I can use OpenGL however I lack the matrix math understanding to fully u...
FLTK, Fast Light Tool Kit has some 2d functionality. It's somewhat like swing and 2d mixed together. It does focus more on the UI aspect but it may help you out. http://www.fltk.org/
3,065,284
3,065,308
What happens when I throw an exception?
I have some technical questions. In this function: string report() const { if(list.begin() == list.end()){ throw "not good"; } //do something } If I throw the exception what is going on with the program? Will my function terminate or will it run further? If it terminates, what value will it return?...
If you throw an exception, all functions will be exited back to the point where it finds a try...catch block with a matching catch type. If your function isn't called from within a try block, the program will exit with an unhandled exception. Check out https://isocpp.org/wiki/faq/exceptions for more info.
3,065,332
3,065,640
Statically linked libraries not running code inside to setup static variables
In a c++ project I am working on, I have a simple c++ file that needs to run some code at the beginning of the program execution. This file is linked into a static library, which is then linked into the main program. I have similar code in other files running fine, that looks something like: bool ____nonexistent_value...
If no symbol is referenced in that particular file then the file will not be included by the linker. You have two options: Remove the file from library and include it (object or source file) directly in the command line for compilation/linking. Then the file should be included in executable. Have a symbol in a file wh...
3,065,643
3,065,656
<function> referenced from; symbol(s) not found
I have a piece of C code that is used from a C++ function. At the top of my C++ file I have the line: #include "prediction.h" In prediction.h I have this: #ifndef prediction #define prediction #include "structs.h" typedef struct { double estimation; double variance; } response; response runPredi...
Likely the name of the function is being mangled*. You need to do the following: extern "C" response runPrediction(int obs, location* positions, double* observations, int targets, location* targetPositions); Which tells it to treat it as a C function declaration. *C++ mangles function names to give ...
3,065,708
3,065,794
strict string to int[long]
Do we have a standard way of converting a char* to int (or long) in a strict way, i.e. we should get proper result only if all characters are digits and can fit in an int (or long) -- some way by using strtol etc.. ? Thus "sbc45", "4590k", " 56", "56 ", should be all invalid using that function.
This is a version close to what @GMan did, but it doesn't accept precedding spaces. e.g. " 101": #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <exception> long strict_conversion(const std::string& number_string) { long number; std::stringstream convertor; convertor <<...
3,065,836
3,065,875
Operator & and * at function prototype in class
I'm having a problem with a class like this: class Sprite { ... bool checkCollision(Sprite &spr); ... }; So, if I have that class, I can do this: ball.checkCollision(bar1); But if I change the class to this: class Sprite { ... bool checkCollision(Sprite* spr); ... }; I have to do this...
In both cases you are actually passing the address of bar1 (and you're not copying the value), since both pointers (Sprite *) and references (Sprite &) have reference semantics, in the first case explicit (you have to explicitly dereference the pointer to manipulate the pointed object, and you have to explicitly pass t...
3,065,903
3,066,008
Issue with class template partial specialization
I've been trying to implement a function that needs partial template specializations and fallen back to the static struct technique, and I'm having a number of problems. template<typename T> struct PushImpl<const T&> { typedef T* result_type; typedef const T& argument_type; ...
The general case must appear before the specializations, otherwise the specializations have nothing to specialize.
3,065,948
3,065,980
C++ Unions bit fields task
Can somebody clear me out why would I use union and with what purpose the same address for the cin'ed variable and bit field (task from the Schildts C++ book)? In other words why would I use union for : char ch; struct byte bit; // Display the ASCII code in binary for characters. #include <iostream> #include <con...
As a union, both ch and bit have an overlapped (shared) memory location. Store a character in it as ch and then reading bit produces the corresponding bit values for the character.
3,066,082
3,066,094
How to keep my topmost window on top?
I will first explain why I need it, because I anticipate that the first response will be "Why do you need it?". I want to detect when the mouse cursor is on an edge of the screen and I don't want to use hooks. Hence, I created one pixel wide TOPMOST invisible window. I am using C++ on Win XP, so when the window is cre...
TopMost, is always a tricky thing. There is no way to override another window that specifies itself as TopMost. Raymond Chen has a good article on this. Also a duplicate of this.
3,066,191
3,066,223
C++ Static Array Initialization - Memory Issue
I have a header file which contains a member variable declaration of a static char array: class ABC { public: static char newArray[4]; // other variables / functions private: void setArray(int i, char * ptr); } In the CPP file, I have the array initialized to NULL: char ABC::newArray[4] = {0}; In the ABC constructo...
How are you printing it? In C++ (and C), strings are terminated with a nul. (\0). If you're doing something like: char arr[4] = {'u', 'h', 'o', 'h'}; std::cout << arr; It's going to print "uhoh" along with anything else it runs across until it gets to a \0. You might want to do something like: for (unsigned i = 0; i <...
3,066,192
3,066,226
AVG Access Denied warning when running the simplest C++ program
I am running a very simple C++ program: #include <list> #include <vector> int main(int argc, char **args) { } I go to the command prompt and compile and run: g++ whatever.cpp a.exe Normally this works just fine. It compiles fine, but when I run it it says Access Denied and AVG pops up telling me that a threat has ...
You're not the first person to encounter false positives by antivirus software. What probably happened is that the antivirus heuristics tripped up on the standard runtime libraries present in your programs, since malware uses them as well. Of course, legitimate software uses them too! The fact that it didn't trip up o...
3,066,557
3,066,812
Exception handling in Boost.Asio
Boost.Asio documentation suggests the following exception handling pattern: boost::asio::io_service io_service; ... for (;;) { try { io_service.run(); break; // run() exited normally } catch (my_exception& e) { // Deal with exception as appropriate. } } The problem with it is that the context o...
There is nothing wrong with the pattern recommended by Boost.Asio. What you should do is package any necessary information for handling the exception along with the exception object. If you use boost::exception (or a type derived from it) for your exception handling, you can very easily attach metadata (including sessi...
3,066,566
3,069,578
Attempt to open browser in C++
I am attempting to open Firefox using C++ on Linux (Ubuntu). However, I get an segmentation fault. What am I doing wrong, and what should I do? std::cout << system("/usr/bin/firefox") << std::endl;
To answer my own question: It works fine, as posted a few times above. The problem was that I was using Netbeans. Netbeans caused a Segmentation Fault when trying to run it. Running outside Netbeans gave the expected result. Nothing wrong with the code, just with Netbeans, strangely enough. So everyone with the same er...
3,066,621
3,068,326
C++ Segmentation fault in binary_function
I'm using Visual Studio 2010 Beta 2 (also tried with NetBeans), and I'm having a segmentation fault in the following code: // One of the @link s20_3_3_comparisons comparison functors@endlink. template <class _Tp> struct less : public binary_function<_Tp, _Tp, bool> { bool operator()(const _Tp& __x, const _Tp& __y) ...
I had the same problem yesterday. This is tried and tested code so there is a very low probability this is causing the crash. Usually there are three possibilities for this crash: another problem is causing a corruption of the data that this function is called on another problem is causing a corruption of your stack c...
3,066,635
3,076,281
Finding the intersection of two vector equations
I've been trying to solve this and I found an equation that gives the possibility of zero division errors. Not the best thing: v1 = (a,b) v2 = (c,d) d1 = (e,f) d2 = (h,i) l1: v1 + λd1 l2: v2 + µd2 Equation to find vector intersection of l1 and l2 programatically by re-arranging for lambda. (a,b) + λ(e,f) = (c,d) + µ...
Here's the solution with a python function. v1 and v2 are the position vectors. d1 and d2 are the direction vectors. def vector_intersection(v1,v2,d1,d2): ''' v1 and v2 - Vector points d1 and d2 - Direction vectors returns the intersection point for the two vector line equations. ''' if d1[0] ==...
3,066,728
3,066,849
Problem with variable argument function in C++
I'm trying to create a variable length function (obviously, heh) in C++, and what I have right now works, but only for the first argument. If someone could please let me know how to get this working with all the arguments that are passed, I would really appreciate it. Code: void udStaticObject::accept( udObjectVisitor ...
If you use a variadic function, you need some way to tell the function how many arguments were passed. For example, printf() and friends take a formatting string that contains format specifiers for each of the passed arguments, and they count the number of format specifiers to determine how many arguments were passed....
3,066,863
3,066,874
What's the difference between a const member function and a non-const member function?
I am very confused about the const version and non-const version member function like below: value_type& top() { return this.item } const value_type& top() const { return this.item } What is the difference between these two functions? In what situation would they be used?
In short, they're used to add 'const correctness' to your program. value_type& top() { return this.item } This is used to provide mutable access to item. It is used so you can modify the element in the container. For example: c.top().set_property(5); // OK - sets a property of 'item' cout << c.top().get_property();...
3,067,235
3,067,361
SDL_ttf and Numbers (int)
int score = 0; char* fixedscore=(char*)score; . . . imgTxt = TTF_RenderText_Solid( font, fixedscore, fColor ); ^^ This doesn't work - looks like fixedscore is empty or doesn't exists. int score = 0; char* fixedscore=(char*)score; . . . imgTxt = TTF_RenderText_Solid( font, "Works fine", fColor ); ^^ Works fine, but......
Casting is not what you want. This code: int score = 0; char* fixedscore=(char*)score; is the equivalent of doing: char* fixedscore = NULL; I assume you are trying to get fixedscore to hold the textual value of the number in score. The easiest way using just standard C++ is via stringstream: std::stringstream strm;...
3,067,330
3,067,336
pass by pointer is not working
#include"iostream" class CMessage { public:int a; CMessage(){} ~CMessage(){} }; void Testing(CMessage *f_pMessage)//l_pMessage is output parameter { f_pMessage = new CMessage(); f_pMessage->a = 1; } int main() { CMessage *l_pMessage =NULL; Testing(l_pMessage); std::cout<<l_pMessage->a;...
Passing by pointer only allows you to modify what is being pointed at. The pointer itself is still being passed by value. Since you want to change a pointer, you can either pass a pointer to a pointer or take the pointer by reference: void Testing(CMessage *&f_pMessage)//l_pMessage is output parameter { f_pMessage...
3,067,816
3,068,050
Can't build full html table in QTextEdit with std::for_each
Here is my code function: void ReportHistory::update(void) { ui.output->clear(); ui.output->setCurrentFont(QFont("Arial", 8, QFont::Normal)); QString title = "My Title"; QStringList headers = QString("Header1,Header2,Header3,Header4,Header5,Header6").split(","); QString html = QString( "<html>" \ "<head>" \...
You are taking a copy of the QString in your functor and so the original is never modified. Try changing it to struct Fill { QString& html_; Analytics::NavHistory::History::value_type prev_; Fill(QString& html) : html_(html) {} // etc... }; and it should work.
3,067,892
3,067,933
Can I catch bad pointer errors in C++?
I was wondering if there is a possibility to catch errors like this in C++: object* p = new object; delete p; delete p; // This would cause an error, can I catch this? Can I check if the pointer is valid? Can I catch some exception? I know I could set the pointer p to NULL after the first object deletion. But just ...
I don't think you can catch this kind of error because I think the result is undefined behaviour. It might do nothing, it might crash, it might just corrupt the memory and cause a problem later down the line. If you found it did something specific with your current compiler you could try and handle that, but it might d...
3,067,998
3,068,059
How to marshall data type unsigned char** in C#?
I'm trying to marshall unsigned char** (which is in a C++ interface) in order to call the method from C#. How can this be done? Is there a list where are C++ data types and C# data types? Thanks!
What is the semantics of this unsigned char**? If it is a byte array, use ref byte[]. If it is a zero terminated string, use ref string. You can find some popular method signatures mapped to c# on the page http://www.pinvoke.net, which may give you the idea.
3,068,088
3,068,141
How to write INT64 to CString
I am coding in c++ windows. INT64 dirID = -1; CString querySQLStr = _T(""); querySQLStr.Format(L"select * from ImageInfo where FolderPath=%64d;", dirID); querySQLStr always like this: select * from ImageInfo where FolderPath= 1214; is it right to use %64d? Ma...
I don't have a windows machine handy to test this on, but I think CString should accept this: querySQLStr.Format("%I64d", dirID); It's probably worth noting that this is windows specific, but since you're using CString I guess that's okay.
3,068,144
12,187,582
Print address of virtual member function
I am trying to print the address of a virtual member function. If I know which class implements the function I can write: print("address: %p", &A::func); But I want to do something like this: A *b = new B(); printf("address: %p", &b->func); printf("address: %p", &b->A::func); However this does not compile. Is it po...
Currently there is no standard way of doing this in C++ although the information must be available somewhere. Otherwise, how could the program call the function? However, GCC provides an extension that allows us to retrieve the address of a virtual function: void (A::*mfp)() = &A::func; printf("address: %p", (void*)(b-...
3,068,198
3,073,626
How to read a multiple line input from command line in c or C++?
For Example: If I need to read a multiple line input like(and I dont know How many lines would be there!!): 1 20 2 31 3 41 I am using something like int main() { string line; while(getline(cin,line) != NULL) { // some code // some code } } Now the program never stops- i.e always it expe...
Just test the variable line for empty each time you read a line. If the use presses enter with no other data, then line will be empty. #include <iostream> #include <string> using std::cin; using std::getline; using std::string; int main(int argc, char *argv[]) { string line; while (true) { getline(...
3,068,231
3,122,668
IPV6 link local multicasting
I'm trying to figure out how to do the equivalent of an IPV4 broadcast using IPV6. I'm creating a non-blocking IPV6 UDP socket. From the side broadcasting i'm literally just doing a sendto "FF02::1" on port 12346. On the listen side I discovered I need to join the group so I did the following: ipv6_mreq membershi...
The interface must be set for locally scoped IPv6 because the addresses are only unique to the interface. In simpler terms the address fe80::1 can belong to both eth0 and eth1 but are completely separate. So this means you need to explicitly send a multicast packet on every up interface that supports multicast, or pro...
3,068,454
3,068,584
Can I have managed code within native code?
Can I have managed code within native code?
There are quite a few ways to do this. You can code in C++/CLI, the managed C++ compiler provided by Microsoft. You can mix managed and native code as you wish (security restrictions may apply). You can go the COM route, and it's natively supported on the .NET side. Harder to program on the native side though, especial...
3,068,513
3,068,535
How can I avoid repeating code with inline functions?
I have repeating code in my work, and I want to get rid of it, so I know that in C++ it is not good idea to use macro, but instead I must use inline function, is it good idea to use this function as inline: list<Data>::iterator foo(int data){ if(dataExists(data)){ list<Data>::iterator i; for(i = dataClass.begin...
What you're doing here is already done by the std::find() function, so it would be better to use that (although it's certainly OK to try implementing these things yourself for the exercise). std::find() also demonstrates a good way to indicate the "not found" condition -- if the item is not found, it returns the iterat...
3,068,562
21,745,254
Accessing typedef from the instance
As in stl containers, why can't we access a typedef inside the class from the class instance? Is there a particular insight into this? When value_type was a template parameter it could help making more general code if there wasn't the need to specify the template parameters as in vector::value_type Example: class T { ...
The answer is use decltype to get the class first. E.g., decltype(t)::value_type Requires C++11. Reference: https://stackoverflow.com/a/13936644/577704
3,068,955
3,069,038
Inheritance and choose constructor from base class
My question is rather simple, but I am stuck. How can I choose the desired constructor from base class? // node.h #ifndef NODE_H #define NODE_H #include <vector> // definition of an exception-class class WrongBoundsException { }; class Node { public: ... Node(double, double, std::vector<double>&...
This simplified code compiles correctly, but doesn't link becuase of missing constructor definition for base class: #include <vector> // definition of an exception-class class WrongBoundsException { }; class Node { public: Node(double, double, std::vector<double>&) throw (WrongBoundsExcep...
3,069,082
3,070,258
Porting getifaddrs to Win XP
I'm trying to port a MacOSX app to windows and I've come up against a problem around getifaddrs. Basically windows does not support it. I'm trying to figure a way to re-implement it (for AF_INET and AF_INET6) but the "equivalent" functionality on windows appears to be nothing like the MacOSX support. Has someone done...
The closest functions on Windows are GetAdaptersInfo and GetAdaptersAddresses. The MSDN documentation is pretty comprehensive, so you should find everything you need.
3,069,123
3,069,980
Odd C++ template behaviour with static member vars
This piece of code is supposed to calculate an approximation to e (i.e. the mathematical constant ~ 2.71828183) at compile-time, using the following approach; e1 = 2 / 1 e2 = (2 * 2 + 1) / (2 * 1) = 5 / 2 = 2.5 e3 = (3 * 5 + 1) / (3 * 2) = 16 / 6 ~ 2.67 e4 = (4 * 16 + 1) / (4 * 6) = 65 / 24 ~ 2.708 ... e(i) = (e(i-1...
Apparently you can't depend on the order of static member initialization, at least in VC++. Here's a simplified example: #include <stdio.h> template<int N> struct one { static const int res; }; template<> struct one<0> { static const int res; }; template<int N> const int one<N>::res = one<N-1>::res; const i...
3,069,182
3,069,230
How can I see the C/C++ #include graph easily?
I'm looking for a tool (preferably, a Visual Studio plugin) that would display all files included by a given file and show all files included by those files and so on.
Doxygen, with the aid of Graphviz, can do that. You first need to edit a configuration file. This won't be easy the first time you do it, but no much editing is needed afterwards.
3,069,200
3,069,220
String::New: what is it?
I am from a Java background and is learning C++. I encountered the following C++ code: String source = String::New("'Hello' + ', World'"); As what I understand so far, this should be a call to static member function 'New' of class 'String'. But, I've searched through the whole header file defining 'String', there is ...
You are correct. That is calling the static method New on the String class. C++ (or STL) doesn't have a native String class, there is a string class, but it doesn't have a ::New method. You'll have to make sure you're reading the right documentation :) It's possible that it's inherited from a base-class, so make sure...
3,069,208
3,069,949
Converting IplImage into 1D vector in OpenCV
I want to convert a mXn IplImage into a (m*n) x 1 1D vector. Can this be done with any function in OpenCV? Any help is greatly appreciated.
cvReshape CvMat* cvReshape(const CvArr* arr, CvMat* header, int newCn, int newRows=0) Changes shape of matrix/image without copying data. And the next example converts a 3x3 matrix to a single 1x9 vector: CvMat* mat = cvCreateMat(3, 3, CV_32F); CvMat row_header, *row; row = cvReshape(mat, &row_header, 0, 1);
3,069,255
3,069,281
Singleton & Multi-threading
I have the following class class Singleton { private: static Singleton *p_inst; Singleton(); public: static Singleton * instance() { if (!p_inst) { p_inst = new Singleton(); } return p_inst; } }; Please do elaborate on precautions taken while implementing ...
In multi-threading that clause if(!p_inst) { p_inst = new Singleton(); } is actually 3 separate actions. You are getting the value of p_inst, setting the value of p_inst and writing the value of p_inst. So get-set-write means that you need to put a lock around p_inst otherwise you can have 2 threads which create...
3,069,324
3,069,345
New datatype which can have numbers upto 100 digits
Note: This was an interview question and may not have an actual use case currently The question was to design a class that can store numbers which are very very large say each number can have 100 digits. This new class is a datatype like int. What are the different types of constructors, overloads and other functions t...
The best approach would be to propose they use am existing, tried and tested C++ wrapper for a bignum library like GMP.