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
6,484,306
6,484,351
Effective C++: discouraging protected inheritance?
I was reading Scott Meyers' Effective C++ (third edition), and in a paragraph in Item 32: Make sure public inheritance is "is-a" on page 151 he makes the comment (which I've put in bold): This is true only for public inheritance. C++ will behave as I've described only if Student is publicly derived from Person. Privat...
Some scenarios where you'd want protected: You have a base class with methods where you know you never want to expose the functionality outside, but you know will be useful for any derived class. You have a base class with members that should be logically used by any class that extends that class, but should never be ...
6,484,362
6,502,993
Using Midi Library To Parse Events And Store In Vector C++
I'm a PHP programmer whose decided to take the plunge into C++ by developing a simple alternative to MissWatson that would allow me to, via the command line with PHP, process a MIDI file through a VST. I started with the Steinberg VST SDK and I've been using this MIDI library: https://ccrma.stanford.edu/software/stk/in...
@the_mandrill is correct, but I just wanted to note that you should be using a VstEvent* type, not VstEvents. A VstEvents structure contains a list of VstEvent objects, and you probably want to break them down into the vector. So some pseudocode for you: // Initialization std::vector<VstEvent *> midiEvents(); // Somew...
6,484,378
6,484,469
How do I prevent trouble arising from std::string being constructed from `0`?
void foo (const std::string &s) {} int main() { foo(0); //compiles, but invariably causes runtime error return 0; } The compiler (g++ 4.4) apparently interprets 0 as char* NULL, and constructs s by calling string::string(const char*, const Allocator &a = Allocator()). Which is of course useless, because the NUL...
This is kind of ugly, but you could create a template that will produce an error when instantiated: template <typename T> void bar(T const&) { T::youHaveCalledBarWithSomethingThatIsntAStringYouIdiot(); } void bar(std::string const& s, int i = 1) { // Normal implementation } void bar(char const* s, int i = 1) ...
6,484,467
6,484,498
Issues in pointer to char* value
What is the issue with this code (It is printing arr[0] correctly but I am getting issues with arr[1]... printing some weird characters): using namespace std; char ** setName() { char * arr[2]; for (int i=0;i<2;i++) arr[i] = (char*)malloc(100); arr[0] = strdup("Robert"); arr[1] = strdup("Jose"); ...
You have two problems in that code: An auto array such as your char * arr[2] is not automatically created with new[]; its storage goes away when the function returns. This is the source of your garbage. You should malloc() or new[] it. char **arr = malloc(2 * sizeof (*char)); strdup() does a malloc(), so you are po...
6,484,484
6,485,439
Template template parameters
It seems understanding template template parameters will kill me :(, Let me explain what misconception I made in my mind which confuses me: template<class T> class B {}; // A templated class Here is other code: template<template<class X> class Z = B> // The problem is in this line for me class BB{}; Note the line in ...
Mankarse has answered your question, but I thought I'd chime in anyway. Template template parameters are just like normal template type parameters, except that they match templates instead of concrete types: // Simple template class template <typename Type> class Foo { Type m_member; }; // Template template class ...
6,484,558
6,489,087
Qt : Update Multiple values on a Button Click
I am facing a problem regarding Signals and Slots mechanism of Qt. The core of the problem is here : My application consists of 2 classes: MainGUI : this class has all the core functionality of the app, and has some variables which store values relevant to the app. Preferences : This class is used to draw and show a Se...
Well, it seems i have figured out the problem. It was simply a matter of emitting the 'variableChanged' signals when the ACCEPT button was clicked. This would update the variables in the MainGUI class. It seems I had found the solution (read my comment), but I had misread the output my program gave, thus I had not real...
6,484,575
6,484,652
Best point to start developing a Database Interface in C++?
I'm working on some server/client based application at the moment. The application is multi-threaded, has plugin-support (via dlopen,...) and should work with multiple databases. Now I'm looking for some hints to start the design of the DBI-ABC. First, I thought about a simple Interface like this: typedef struct { ...
Ive never designed something like this myself, but one example I have seen used before is a setup where database records were stored in a structure that was essentially a std::map<std::string, boost::any>, only the types described themselves, so you knew what they were, unlike boost::any. SQL queries could then be run...
6,484,699
6,485,116
fatal error C1083: Cannot open include file: 'vld.h': No such file or directory
all, i tried to use Visual Leak Detector, and followed the instructions: Visual C++ 2010: Go to View ->Property Manager, select Microsoft.Cpp.Win32.user. Select VC++ Directories and then "Include files" from the tree. Add the include subdirectory from the Visual Leak Detector installation directory. Move it to the bott...
In the "Include Directories" field, add C:\Program Files\Visual Leak Detector\include;$(IncludePath) and in the "Library Directories" field type C:\Program Files\Visual Leak Detector\lib\Win32. (or \Win64, like in the instructions you have followed). Note that this setup will get you through the build phase, if the pat...
6,484,728
6,484,825
Non-blocking connect timeout
I'm perform non blocking connect to server. What an appropriate timeout value to be used in select to consider the server down/busy? P.S. Connect can fail since server is down or busy. In case server is down I always will always end with select timeout. More interesting case is when server is busy. IMHO 1 sec is en...
Packets can be lost in which case the node will resend it after a timeout so do not use a value that's just enough for a handshake. You can play a bit with tcpdump, break the connection (unplug the ethernet cable) and see what's happening. Something like 10-20 seconds should be fine, but this is depends on how importan...
6,484,752
7,216,991
Delete IE9 Cache and Cookies
My app works with Web Browser Control embedding IE9. I have changed the registry of IE to write it's cache/cookies into some own temp folder (I wanted that every instance will write it's cache and cookies to a separate location). The writing is done perfectly (each IE instance has it's own cache folder). From the proce...
WinInet functionality described above - do work. It was tested against wireshark and some other sniffers and validated the clear cache/cookies solution.
6,485,130
6,485,139
c++ find char in vector of unsigned chars
I have the problem with the following code: message is vector<unsigned char> vector<unsigned char>::iterator pos = message.begin(); vector<unsigned char>::iterator start = message.begin(); vector<unsigned char>::iterator end = message.end(); pos = find(start, end, ' '); I got the error: error: no matching function f...
Are you including <algorithm>?
6,485,419
6,485,521
declaring a class with struct keyword and vice versa
But of course we shouldn't even think of doing such things, I know, but still this is quite interesting: class A; //declaration struct A {...}; //definition struct B; //declaration class B {...}; //definition When I think about it, I don't see any problems if such a thing were really allowed(because struct and class ...
It is allowed according to the standard, but as some compilers warn about it, it is not very useful. I believe the warning is/was caused by MSVC using a different name mangling for structs and classes, which would make it even less useful... On request from @Armen: 7.1.5.3 Elaborated type specifiers, p3 ... in any el...
6,485,461
6,486,151
c++ find() for map of member function
I have two classes with inheritance. I want to allow the classes to store their function in one map. How can I create the find function by the key? And will the inheritance of the function work (MyClass_2 does not have its own doSmth() function, it should add the doSmth() from MyClass)? My attempt is below.: template<c...
As Chris says, your findFunc should return the actual function: MyFunction findFunc(string key) { const map<string, MyFunction>::const_iterator it = functionMap.find(key); return it == functionMap.end() ? NULL : it->second; } Further, if you only store the function pointer to a member function, you lose track of t...
6,485,496
6,485,519
How to get std::vector pointer to the raw data?
I'm trying to use std::vector as a char array. My function takes in a void pointer: void process_data(const void *data); Before I simply just used this code: char something[] = "my data here"; process_data(something); Which worked as expected. But now I need the dynamicity of std::vector, so I tried this code instead...
&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken). Assu...
6,485,513
6,485,574
Will the c++ compiler optimize away unused return value by `reference`?
Before someone jumps and says Profile before optimize!, this is simply a curiosity question and stems from this original question. If I am returning by reference the same object, would that get optimized away if not used? For example, I have a Vector<> that has various mathematical functions (assume I am not using oper...
References as arguments or return statements are usually implemented in a manner similar to pointers and the cost is minimal (negligible in most case). Depending on the calling convention it can be a single store in a register. As to whether the return can be optimized away, unless the compiler is inlining the code no,...
6,485,537
6,485,554
Cast an iterator of a vector of shared_ptr type
How can I cast an iterator of a vector of shared_ptr type? Consider following example: typedef boost::shared_ptr < MyClass > type_myClass; vector< type_myClass > vect; vector< type_myClass >::iterator itr = vect.begin(); while(itr != vect.end()) { //Following statement works, but I wish to rather cast this //t...
You do not want to cast, but rather extract a reference to the object: MyClass & obj = *(*it); // dereference iterator, dereference pointer obj.doSomething();
6,485,601
6,485,616
const problem in VS2010
I have the shortest question possible: Why does this not work in VS2010? string keyword("lookuptable"); const int kwSize = keyword.size(); char oldBuffer[kwSize+1]; It works perfectly in GCC. VS2010 tells me that "expression must have constant value" I am using Win32 console application / empty project. I am using ...
The size of an array must be an integral constant expression, or ICE (which means that it must be known at compile-time). You can use a const int in an ICE, but only if its initializer is itself an ICE. A function call, like keyword.size() is not usable in an ICE, so kwSize is not usable in an ICE. If it "works perf...
6,485,705
6,485,728
Why does this simple std::thread example not work?
Tried the following example compiled with g++ -std=gnu++0x t1.cpp and g++ -std=c++0x t1.cpp but both of these result in the example aborting. $ ./a.out terminate called after throwing an instance of 'std::system_error' what(): Aborted Here is the sample: #include <thread> #include <iostream> void doSomeWork( voi...
You have to join std::threads, just like you have to join pthreads. int main( int argc, char *argv[] ) { std::thread t( doSomeWork ); t.join(); return 0; } UPDATE: This Debian bug report pointed me to the solution: add -pthread to your commandline. This is most probably a workaround until the std::thread c...
6,485,791
6,485,843
C++: instantiate a templated class according to an argument
I often find the need to use the following pattern: template<typename T> class SomeClass : public Base { SomeClass(const T& t) {...} ... }; template<typename T> SomeClass<T>* makeSomeClass(const T& t) { return new SomeClass<T>(t); } And to use it: Base* = makeSomeClass(123); This is useful when I don't want ...
No, there is no way to do this without an extra make function. The reason it doesn't work with constructors is because it would be ridiculously complicated. Consider this: template <typename T> struct Foo { Foo(const T& val) { ... } Foo(const Foo<T>& other) { ... } // Copy constructor }; Foo<int> x; What if I...
6,485,812
6,485,919
Implementing Similar Classes
I am new to C++ programming, and I am making Pong in Visual C++. My game will have two game modes, multiplayer and singleplayer. Right now, I am planning on having a separate class for the singleplayer paddles and the multiplayer paddles. (So I'll have PaddleMP RpaddleMP, LpaddleMP; and PaddleSP RpaddleSP, LpaddleSP;, ...
IMO, you have two problems here. First, I think the names you've chosen (single player vs. multiplayer) are poor. Second, I think the paddle itself should be independent of the input that moves the paddle. Therefore, there should really only be one paddle type. You can tell it to move up or down and it'll move the dire...
6,486,046
6,486,106
PostMessage() succeeds but my message processing code never receives the message
In my C++ application's GUI object I have the following in the main window procedure: case WM_SIZE: { OutputDebugString(L"WM_SIZE received.\n"); RECT rect = {0}; GetWindowRect(hwnd, &rect); if (!PostMessage(0, GUI_MSG_SIZECHANGED, w, MAKELONG(rect.bottom - rect.top, rect.right - rect...
Hacking a custom message loop is something you'll live to regret some day. You hit it early. Don't post messages with a NULL window handle, they can only work if you can guarantee that your program only ever pumps your custom message loop. You cannot make such a guarantee. These messages fall into the bit bucket as ...
6,486,085
6,486,312
Simple operator+ problem eluding me
I'm trying to add two lists of uint8_t as though the list were individual integers, and I'm getting some weird values: 0x1000 + 0x100 + 0x10 -> 0x1210 ????? Code is as follows: // values 0x123456 stored as: {12, 34, 56} integer operator+(integer rhs){ // internal list called 'value' std::list <uint8_t> top = va...
next_carry = ((*i + *j + carry) > 255); is the correct answer, due to the extra 1, since *i + *j + carry can equal the minimum std::min(*i, *j)
6,486,087
6,486,486
The procedure entry point EnumerateLoadedModulesW64 cound not be located in the dynamic link library dbghelp.dll
all, i tried to use Visual Leak Detector in my MFC project, and when i tried to debug the program, i got this error, whats this? cheers daiyue
It is a DLL Hell problem. This function only exists in DbgHelp.dll version 5.1 and greater. You can get an up-to-date version by downloading the Debugging Tools for Windows. It is included in the Windows SDK lately, unfortunately. That's another kind of DLL Hell. Do ping the support for Visual Leak Detector, they s...
6,486,113
6,486,131
How do I flush extraneous characters from cin?
char buff[3]; cout<<"From: "; cin.getline(buff, 3); //something something cout<<"To: "; cin.getline(buff, 3); How can I clear buffer at comment so extra chars don't go to my second cin?
One way is to use istream::ignore: cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); This will skip the maximum possible number of characters up until a newline is read. For what it's worth, though, you should probably not be using istream::getline, as it works with raw C-style strings. A better option w...
6,486,192
6,489,105
Firefox Extension/Addon Binary Component Backward Compatibility
I have been reading up and looking at ways to compile binary components for Firefox extensions. Since Firefox 5 is being released (and 6 & 7 coming up soon) I was wondering if binary components are worth making anymore or just use a standalone executable to run the functionality I want. I got a sample binary component ...
Your error message should be due to the XPT file not being recognized correctly (Components.interfaces.IMyComponent is undefined). Maybe that's because it is in the wrong directory - in Firefox 3.6 you don't declare it in the chrome.manifest file, instead it has to be located in the compoments/ directory along with you...
6,486,308
6,486,351
Getting the type specifier given an object
I am trying to write a template function that will take an STL container and will display all the occurrences of the elements in it and the number that they have occurred. I am planning to use a map, iterate through the container and either add a new element if it does not exist or increment the count of occurrences fo...
How about something like this: #include <map> #include <iterator> template <typename Iter> void histogram(Iter begin, Iter end) { typedef typename std::iterator_traits<Iter>::value_type T; std::map<T, size_t> h; while (begin != end) ++h[*begin++]; // now h holds the count of each distinct element } Usage: ...
6,486,369
6,486,389
is it possible to recreate for loop in c++ with a function
I recently wrote a simple macro because I was so tired of typing the same thing for every vector I needed to loop through: #define FORVEC(a,b) for(int b=0;b<a.size();b++) so I could do something like vector<sometype> stuff FORVEC(stuff,i) { stuff[i].dosomething(); } I try to avoid using macros since I was told ...
There's a significantly more advanced version in BOOST_FOREACH that you can use in C++03. What you're talking about isn't in C++03 but is in C++0x with the introduction of lambda expressions. std::for_each(vec.begin(), vec.end(), [&](const T& ref) { ref.do_something(); }); Specifically for this use, there's even a...
6,486,432
6,486,631
Variadic template templates and perfect forwarding
This question on the object generator pattern got me thinking about ways to automate it. Essentially, I want to automate the creation of functions like std::make_pair, std::bind1st and std::mem_fun so that instead of having to write a different function for each template class type, you could write a single variadic te...
That's exactly right. I would expect it to work. So I think that GCC is in error with rejecting that. FWIW: #include <utility> template <template <typename...> class TemplateClass, typename... Args> TemplateClass<Args...> make(Args&&... args) { return TemplateClass<Args...>(std::forward<Args>(args)...); } int mai...
6,486,447
9,258,750
Multiple problems linking mysqlpp_d.lib
Today I added a class which manages the connection to a MySQL Server. It will be multi-threaded, so I want to use mysql++. I downloaded the newest version and compiled it in debug mode without any errors. Once I added the compiled mysqlpp_d.lib to my solutions, and of course the other requirements too (mysql 5.0 includ...
Define MYSQLPP_NO_DLL in Project Properties->C/C++/Preprocessor
6,486,746
6,491,244
Looking for one liner example how to bind and insert a null value into a database using ODBC API
The function is SQLRETURN SQLBindParameter( SQLHSTMT StatementHandle, SQLUSMALLINT ParameterNumber, SQLSMALLINT InputOutputType, SQLSMALLINT ValueType, SQLSMALLINT ParameterType, SQLULEN ColumnSize, SQLSMALLINT DecimalDigits, SQLPOINTER ...
Its not one line as such but SQLLEN ival; ret = SQLBindParameter( stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 100, 0, NULL, 0, &ival ); /* * before execution is called */ ival = SQL_NULL_DATA; That inserts a NULL value as a CHAR(100) datatype. Pick the actual datatype to match what your column type is, but...
6,486,888
6,486,924
C++ program on determining triangle
I need help with the following code that requires me to: Declare 3 double type variables, each representing one of three sides of a triangle. Prompt the user to input a value for the first side, then Set the user’s input to the variable you created representing the first side of the triangle. Repeat the last 2 steps t...
if(a==b && b==c) // all sides equal cout << "Equilateral triangle\n"; else if(a==b || a==c || b==c) // at least 2 sides equal cout << "Isosceles triangle\n"; else // no sides equal cout << "Scalene triangle\n";
6,487,013
36,255,106
Programmatically determine whether exceptions are enabled
Most C++ compilers allow for exceptions to be disabled. Is there a way to determine it from the code without using compiler-specific preprocessor macros, such as _CPPUNWIND for MSVC? Ideally at compile time.
Since WG21 in 2014, there is a recommended macro to use __cpp_exceptions It will have the value 199711 if exceptions are supported and the compiler conforms to C++98. Other similar feature macros are shown here.
6,487,343
6,487,368
C++ Singleton Implementation - Problems with static
It has been a while since I've programmed in C++. I was trying to implement a singleton class, but I get an unresolved external symbol. Can you guys point out out to resolve this problem? Thanks in advance! class Singleton { Singleton(){} Singleton(const Singleton & o){} static Singleton * theInstance; pub...
You have declared Singleton::theInstance, but you have not defined it. Add its definition in some .cpp file: Singleton* Singleton::theInstance; (Also, Singleton::getInstance should return a Singleton& rather than a Singleton.)
6,487,397
6,487,411
cmath asin() problems
Hey so i managed to locate the problem in some graphics math i am coding, and apparently when i reach this line of code: float test3= asin(test2); where test2= 0.017409846. to my understanding 'asin' is 'arc sin' which is 'inverse sin' (what i want) the result of this line of code however is test3 = 0.017410725. when p...
Your calculator is set to degrees mode. The asin() function returns radians. Degrees and radians are related by the formula: degrees = (180/π) * radians
6,487,693
6,487,893
Code for searching for a string in a binary file
I have asked this question a few days ago: How to look for an ANSI string in a binary file? and I got a really nice answer, what later turned into a much harder question: Can input iterators be used where forward iterators are expected? what is now really not on a level what I could understand. I am still learning C++ ...
Your requirement specification is unclear, for example - where does "121" appear in "12121"... just at the first character (after which searching continues at the 4th), or at the 3rd as well? The code below uses the former approach. #include <iostream> #include <fstream> #include <string> #include <string.h> int main...
6,487,918
6,488,645
Signed right shift: which compiler use logical shift
I tested right shift with Visual Studio, Ubuntu's GCC, Intel compiler, MinGW. All shift in the sign bit. I guess Xcode's GCC does the same. I know that the behavior is implementation specific, but it looks like that all major desktop/server compilers implement arithmetic shift. Are there any widely used compiler that ...
C runs on a lot of different architectures. I mean a lot of different architectures. You can get C code running on an embedded DSP and on a Cray supercomputer. Most of the "implementation-defined" parts of the C standard that people take for granted really only do break on obscure architectures. For example, there a...
6,488,084
6,488,094
How do I delete map instance?
map<long long, vector<SoundInfo *> > DataCenter::getCopySoundListMap(){ lock(); map<long long, vector<SoundInfo *> > copyMap(m_soundListMap); unLock(); return copyMap; } I have this method. It makes a copy of map and returns the copy. I am calling this method like this map<long long, vector<SoundIn...
It's a local variable, so it gets released when it goes out of scope... that is, when the {...} block it's inside reaches that }. It doesn't matter whether it's a function scope, a for or while loop, just an arbitrarily blocked group of statements... the variables introduced inside that block have their destructors in...
6,488,308
6,488,434
A sleep in thread causes memory leak
I peek into my ancestor's code and found out a leak in the following situation: 1) Launch application b) After application is launched, close the applicaiton within 4 secs The leak message: f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {58509} client block at 0x016DFA30, subtype c0, 68 bytes long. Subs...
It sounds like the worker thread is not given a chance to close itself properly after your app closes, since the process ends before it exits. The operating system is usually pretty good at cleaning up resources on its own, so it may not be a problem. However, it's probably best if you wait for that thread to exit befo...
6,488,323
6,488,343
Why does an empty vector call the value type's default constructor?
Using g++, I observe that creating a vector of size zero calls the vector's parameterized object type's constructor once. It then is deleted. Why does this happen? #include <iostream> #include <vector> using namespace std; class s { public: s() { cout << endl << "default s constructor" << endl; } ~s() { co...
Because you're explicitly passing an initial size, which calls a constructor that has another parameter whose default value is s(). Just leave out the (0) (i.e. std::vector<s> v;) and it won't happen. For completeness, the Standard 23.2.4-2 defines the constructor you're calling as:     explicit vector(size_type n, co...
6,488,715
6,488,743
C Strings: Simple Question
I have three variables initialised below : char c1[] = "Hello"; char c2[] = { 'H', 'e', 'l', 'l', 'o', '\0'}; char* c3 = "Hello"; I am aware that c1 and c2 are the same, and that they are both strings because they are terminated by \0. However, c3 is different from c1 and c2. Is this because c3 does not terminate wit...
In terms of C, the most pertinent difference between c3 and the others is that you are not allowed to attempt to modify the underlying characters with c3. I often find it helpful to think of it like this: char *xyz = "xyz"; will create a modifiable pointer on the stack and make it point at the non-modifiable character...
6,488,790
6,489,126
Is this a correct implementation of operator<< / >>?
are these correct implementations of the operator<< and >> for bitshifting? for some reason, in my operator/, where it only involves these 2 operators, something is allowing for a silly jump that is causing division to be done incorrectly. // the value is stored msb in a list of uint8_t // so 0x123456 will be s...
template <typename T> Does this really need to be parameterized? It would seem that any shift quantity can be stored in a size_t, and converting to size_t implicitly or explicitly would be a good idea before starting the rest of the process. integer operator<<(T shift){ Usually binary operator functions are best impl...
6,488,847
6,489,010
read entire binary file into an array in single call c++
I am trying to read a binary file into an array of structure struct FeaturePoint { FeaturePoint (const int & _cluster_id, const float _x, const float _y, const float _a, const float _b ) : cluster_id (_cluster_id), x(_x), y(_y), a(_a), b(_b) {} Feat...
This is wrong: features.reserve( size/sizeof( FeaturePoint )); You're about to read data into the vector, you should resize it, not just reserve, like this: features.resize( size/sizeof( FeaturePoint )); This also is wrong: file.read( reinterpret_cast<char*>(&features), size ); You're not writing over the vector's ...
6,488,899
6,492,810
How to input data from a CSV file in C++?
How to input data (numerical values) in a CSV file (values separated by commas), to a C++ file-executable to be run in a terminal to see the motion of a robot in rviz? The data contains the position of robot joints at different times; part of the CSV file contains values like these, each column representing each joint...
Since there are supposed to be 17 entries per line, I would read each line into a string, and then carve the string into 17 values using a string stream. Here is some outline code that does the job; it can certainly be enhanced and would have to be adapted to fit your program. #include <iostream> #include <sstream> #i...
6,489,128
6,489,265
How exactly would one implement auto update on assignment
Consider the following code: struct data { int foo; int bar; }; data a; a.foo = 200; a.bar = 300; static void update(data* a, int rspec) { if (!rspec) //my data management { 3rdPartyApi->CreateStream(); 3rdPartyApi->PushData(a->foo); 3rdPartyApi->PushData(a->bar); 3rdPartyApi->Clos...
Yes, you can. Use class methods for this. Pass a static method from your class to the 3rd party API as an update function. class data { public: void set_foo(int new_foo); void set_bar(int new_bar); int get_foo() const; int get_bar() const; // This is the update signature which the 3rd party API ca...
6,489,351
6,489,381
nested-name-specifier
I have a code like: namespace mymap { template <class Key,template <typename T > class Allocator> myownmap { typedef pair<const unsigned int, Key> typename _myPair; typedef multimap<unsigned int, Key,less<Key> ,Allocator<_myPair> > typename _entriesType; } } It compiles successfully (and works)...
The typename is not needed there, and is therefore not allowed. MSVC do not parse templates properly until they are actually used, so some errors are not found until later.
6,489,425
6,489,484
Identifying the type of the object during polymorphism
Let us say that I have a class A which is extended by B and C. Now, for want of polymorphism, I use base class pointer to point to the derived class object. A *a = new B(); OR A *a= new C(); Now, let us say that I have executed few statements. now, I am interested in identifying the type of the object that the base c...
The direct way would be to use dynamic_cast: B* b = dynamic_cast<B*>( a ); if( b != 0 ) { // the object can be cast to class B safely } however the real answer is you don't need to when you do polymorphism right - you have to use virtual functions and implement them appropriately in derived classes so that you can b...
6,489,627
6,489,760
How to use multiple source files to create a single object file with gcc
I'm using the -c option with g++ to create a bunch of object files, and it's only letting me specify one source file for each object file. I want to have multiple files go into some of them. Is there any way to do this?
Others have mentioned archive, but another option is Unity builds. Instead of: g++ -c file1.cpp file2.cpp Create a separate "unity file" // This is the entire file (unity.cpp) #include "file1.cpp" #include "file2.cpp" // more if you want... Then g++ -c unity.cpp This also has the advantage of faster compilation and ...
6,489,779
6,489,933
Protocol/Infrastructure for communicating between applications over a network
I have a C++ application that currently uses a simple TCP/IP client/server model to communicate between 2 instances of itself. This works fine on a local network, but I would like this to be used across an external network. Currently, maybe due to firewall issues, it is not able to connect across an external network. I...
The bane of modern internet communications is NAT. Due to NAT (which shouldn't be confused with a simple firewall) a large portion of hosts on the internet don't have a public address and thus can't (easily) accept incoming connections. NAT breaks the internet so badly that people are moving to a totally different sche...
6,489,792
6,489,824
What does _stscanf_s do?
I saw this function in some code and I can't find documentation on google about it. Can someone explain what it does and are there any alternatives to this ? Thanks.
See http://msdn.microsoft.com/en-us/library/tsbaswba%28VS.80%29.aspx: it is a generic name for sscanf_s. EDIT: which is conveniently documented here. _stscanf_s is in TCHAR.H on Windows platforms. You can probably get away with using sscanf_s or swscanf_s.
6,489,852
6,489,877
Torrent Library for C++, Windows
I'm looking for a library which allows my C++ application (run in Windows) to download torrents. I can't, however, find any out there. Can someone please point me in the right direction? Thanks in advance.
http://www.rasterbar.com/products/libtorrent/ It is used in Halite, which is a pretty good client :) The library has a BSD license, and seems to be used in quite a few clients: http://www.rasterbar.com/products/libtorrent/projects.html
6,489,991
6,490,540
precompiled Headers C++
assume We have c++ project (static)library 'A' that uses DirectX headers as precompiled headers to implement base graphic engine. and we have project (static)library 'B' that uses 'A' headers as precompiled headers to implement game engine and we have c++ project 'C' that uses two previous projects to implement a game ...
Precompiled headers should NEVER be exposed to users of a library. They are a detail of the implementation of a library; nothing more. PCHs are something that .cpp files include; they should never be included from a header file. Remember: a header file should include only what that header file absolutely needs to in or...
6,490,185
6,490,856
XML hierarchy with Boost::serialization
I've recently begun to use Boost::serialization for research work and although it is extremely powerful and easy to use, I still have a little trouble with the final xml format. I have a hierarchy of classes and when serialized, each subclass is nested within it's own tag in the xml output. This subClass tag is created...
Boost.Serialization is not intended for being a mechanism to write to a specific file format. It is a way to dump a class's data to a file, and then read that data with this program again. The format is not something that should concern you. If you are using a specific file format, then what you want, as Merlyn suggest...
6,490,499
6,490,625
How can I derive my own stream from a standard stream?
How can I derive my own stream from a standard stream? In C# language, there is a Stream class, but C++'s streams are too complex. I want something like this: class my_stream : public std::stream { // How to derive? }; void using_a_stream(std::stream* s) { *s << "Hello world"; } void main() { std::stream s1; ...
I think there are three levels of answer to this question: Level 1: It is complicated, especially if you are completely new to C++, stop right now. Only if you feel adventurous, continue to level 2. Level 2: Use some library that makes creating streams easier. I would suggest using Boost.IOStreams library. It makes cre...
6,490,569
6,491,535
How to Integrate matlab with Qt on windows 7
I'm stuck in a very important part of my project as i need to call Matlab functions form Qt 4.7.3 since i use the Qt for my interface (UI) and i want to call matlab function that return results and it appears on Qt UI i searched many and many and i didn't find any thing that can help even with traditional C++
this will get you started. Basically you compile a dll from within Matlab, and call the dll from your c++ code. Note however: it can take a looong time to load the dll since it loads the matlab runtime etc. Also, all computers you want to use it on need the matlab runtime installed. A newer option is this one. Haven't ...
6,490,664
6,490,933
native C++ dll/C# Problem of memory
I have this error Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Do you know why? I am realy stuck... My Code : Native c++ extern "C" void __declspec(dllexport) Mafonc(string nom); void __declspec(dllexport) Mafonc(string nom) { st...
in my C++ code the string is a real string coming from String.h. There is no type named "string" in the <string.h> header, only std::string from <string>. The pinvoke marshaller cannot create C++ objects. You must use a C string: extern "C" __declspec(dllexport) void Mafonc(const char* nom) { std::string tom(no...
6,490,741
17,989,459
Does Oracle provide public Symbol Files (PDB) for OCCI/OCI?
OTN Thread: Does Oracle provide public Symbol Files (PDB) for OCCI/OCI ? When debugging an application under Windows (with Visual Studio or WinDBG) that makes use of OC[C]I it would often be convenient if there be symbol files (PDB files) for the Oracle OCI/OCCI libraries. (public symbol files, just as Microsoft make...
No, Oracle does not provide these files, neither for OCCI nor for OCI. (at least not for version 10, nor for 11) The reason really escapes me, but trying to get behind any reasoning of Oracle is a sure road to insanity. I should add a quote from the Oracle forums: unfortunatly not - only in case of a bug support can r...
6,490,806
6,490,919
Nested templates and static member initialization
I want to create an inner template class that will be dependent on the outer class. I'm having trouble defining its static members: template<typename T1, typename T2> struct B { template<typename T3> struct C { static T3 m_c; }; static T1 * pT1; }; template<typename T1, typename T2> template<typename ...
I'm guessing your compiler fails at parsing the < sign as the opening bracket of template declaration. Try to tell it explicitly that it is a template, not a less-than operator: template<typename T3> T3 B<T1,T2>::template C<T3>::m_c;
6,491,163
6,492,317
Is it possible to write these pure_assert and const_assert macros?
The GCC __attribute__((pure)) and __attribute__((const)) allow functions to be declared as non–side-effecting and referentially transparent, respectively; let's say I want to write pure_assert and const_assert macros, whose argument must be an expression of the appropriate level of strictness, that is: assert(oops_a_si...
Does gcc enforce that pure and const functions cannot call non-pure or non-const functions, respectively? If so, you could define a properly attributed function template which takes a function pointer as a template parameter, and let the macro expand to an invocation of that function template. I assume you need to su...
6,491,251
6,491,306
Multi-dimensional vector initialization
I have following std::vector declaration: std::vector<std::vector<std::vector<int> > > m_input; I am initializing it as follows: m_input.resize (100); m_output.resize(100); for (int i = 0; i < 100; ++i) { m_input [i].resize(100); m_output[i].resize(100); for (int j = 0; j < 100; ++j)...
std::vector<T> has a constructor that takes two arguments, a number of elements and an initial value. In your case, you want to initialize m_input with 100 copies of a std::vector<std::vector<int> > , so it'd be : m_input(100, X). Now, that X in turn is a vector of 100 std::vector<int>, which in turn contains a hundred...
6,491,430
6,491,524
checking class in c++ templates without class instance
I need to write template which generates some code depending on whether template parameter is instance of of some class. The template can be generated for all classes but only in case the class is subclass of other class the code should be executed. The problem is that function that should be implemented does not recei...
You can use template specialization or boost::is_base_of from the boost traits library Or of course write your own traits, but shouldn't, for you have not mastered templates yet. Using specialization, you could template<T> class A { void somefunction() { // generic version } }; template<> class A <Foo> { v...
6,491,566
6,491,964
Getting the machine serial number and CPU ID using C/C++ in Linux
How can I get the machine serial number and CPU ID in a Linux system? Sample code is highly appreciated.
Here is what the Linux kernel seems to use: static inline void native_cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx) { /* ecx is often an input as well as an output. */ asm volatile("cpuid" : "=a" (*eax), "=b" (...
6,491,755
6,492,153
Qt layout and splitter difference
I want to ask that in Qt what is the difference between: layout horizontally and: lay out horizontally in splitter Similarly: layout vertically and: lay out vertically in splitter When should either be used?
Qt "Splitters" are layouts that give you a movable handle between the embedded frames, so that the user can adjust the relative size of each by dragging that. You'd use a splitter instead of an ordinary layout if the ability to adjust the relative sizes of each is a reasonable user expectation; for example, the typical...
6,491,832
6,517,560
How to get Control/Windows Handle/AutomationElement that receives mouseclicks at specific point?
I am trying to get a control at a specific screen coordinate which I have given. Now I want to know which control would receive a mouse-click. (The control is in another application in an UI Automation scenario.) Also, let me say, that Control, Windows Handle and AutomationElement are all the same to me, since they are...
Since there are no answers (or am I too impatient?), there is.. not a solution but rather a workaround I have found. Actually, what I would have wanted is a deep search that is parameterizable (which unfortunately does not exist, though I suppose you could do it recursively yourself). So.. the workaround is: I make the...
6,491,934
6,492,184
How is long long implemented in C++?
In C++, as far as I know, all data types are implemented as classes. ( Don't know if it is right, but I read it as a justification for statements such as int a(5); which calls the parametric constructor of int. ) If so, how are long and short implemented? I just found out that long long and short short are valid types ...
On the particular question, long long is implemented by the compiler in a compiler + platform specific way (usually more platform than compiler dependent). As to the original misconception, no, not all types are classes in C++. The languages tries to provide a uniform syntax in as much as possible for all types, trying...
6,491,938
6,492,030
Explanation for Why int should be preferred over long/short in c++?
I read somewhere that int data type gives better performance (as compared to long and short) regardless of the OS as its size gets modified according to the word size of the OS. Where as long and short occupy 4 and 2 bytes which may or may not match with the word size of OS. Could anyone give a good explanation of this...
int is traditionally the most "natural" integral type for the machine on which the program is to run. What is meant by "most natural" is not too clear, but I would expect that it would not be slower than other types. More to the point, perhaps, is that there is an almost universal tradition for using int in preferenc...
6,491,955
6,499,125
How to get the Object being pointed by a shared pointer?
I have a query. Can we get the object that a shared pointer points to directly? Or should we get the underlying RAW pointer through get() call and then access the corresponding object?
You have two options to retrieve a reference to the object pointed to by a shared_ptr. Suppose you have a shared_ptr variable named ptr. You can get the reference either by using *ptr or *ptr.get(). These two should be equivalent, but the first would be preferred. The reason for this is that you're really attempting to...
6,492,016
6,492,723
Convert historical time to GMT
I need to convert some string times in the format "2011061411322100" into GMT - my first attempt is below. However, the problem is that the times are coming from another PC and is a historical time. So I am not getting the times in real time so I cannot simply get the GMT from the local time on the box that my code i...
The obvious reliable solution would be to use UTC (which has no daylight savings) for the time stamp you're sending over. Using any time system that has inherent ambiguity (there is one hour of overlap each year where you can get the same time stamps on a different time) will make it impossible to have a fool-proof met...
6,492,367
6,492,796
Stealing inside the move constructor
During the implementation of the move constructor of a toy class, I noticed a pattern: array2D(array2D&& that) { data_ = that.data_; that.data_ = 0; height_ = that.height_; that.height_ = 0; width_ = that.width_; that.width_ = 0; size_ = that.size_; that.size_ = 0; } The pattern obvi...
Here is the recommended pattern: array2D(array2D&& that) : data_(std::move(that.data_)), height_(std::move(that.height_)), width_(std::move(that.width_)), size_(std::move(that.size_)) { that.data_ = 0; that.height_ = 0; that.width_ = 0; that.size_ = 0; } Naturally if the data memb...
6,492,408
6,492,513
Pointer incrementing in C++
What does this mean: that a pointer increment points to the address of the next base type of the pointer? For example: p1++; // p1 is a pointer to an int Does this statement mean that the address pointed to by p1 should change to the address of the next int or it should just be incremented by 2 (assuming an int is 2 ...
Pointer arithmetic doesn’t care about the content – or validity – of the pointee. It will simply increment the pointer address using the following formula: new_value = reinterpret_cast<char*>(p) + sizeof(*p); (Assuming a pointer to non-const – otherwise the cast wouldn’t work.) That is, it will increment the pointer b...
6,492,410
6,492,679
Assigning string literals to char*
Is the following code legal, deprecated or illegal in C++0x? char* p = "foobar"; I originally asked this question here as a comment.
The conversion char* p = "foobar"; is deprecated in C++98/C++03, and has been removed (that is, §4.2/2 removed) in C++0x. So, the code is not valid in C++0x. However, MinGW g++ 4.4.1 still only emits a warning, not error. C++98/C++03 §4.2/2 (which is removed in C++0x): A string literal (2.13.4) that is not a wide s...
6,492,581
6,492,633
Conditional compilation for move operations
How can I check whether my compiler supports rvalue references or not? Is there a standard preprocessor macro, or do different compilers have different macros? Ideally, I would want to write this: #ifdef RVALUE_REFERENCES_SUPPORTED foobar(foobar&& that) { // ... } #endif
I'm not aware of any standard preprocessor macro, but: Visual Studio introduced support in VC2010, whose internal version is 1600, so you can check with _MSC_VER >= 1600 GCC has supported rvalue references since version 4.3, so you can check for that version along with __GXX_EXPERIMENTAL_CXX0X__ Clang defines __has_fe...
6,492,612
6,492,670
C++ enumerations and compiler dependency
I currently have code with an enum where one value is set and the rest are left to be set by the compiler using the previous value +1, or so I hope. Is this functionality within an enumerated type compiler dependant, an example is below to clarify. enum FUNC_ERROR_CODE { FUNC_SUCCESS, FUNC_ERROR_1 = 24, ...
It is safe to assume that: Enumeration Declaration [dcl.enum] The identifiers in an enumerator-list are declared as constants, and can appear wherever constants are required. An enumerator-definition with = gives the associated enumerator the value indicated by the constant-expression. The constant-expression sha...
6,492,664
6,492,807
How to create a mock class with operator[]?
I am having a class with operator[], like this : class Base { public: virtual ~Base(){} virtual const int & operator[]( const unsigned int index ) const = 0; }; How can I create a mock class using google mock framework for this method? I tried this : class MockBase : public Base { public: MOCK_CONST_METH...
The MOCK_METHOD# macros won't work on operators. The solution given in this message says to create a regular method for mocking: class Base { public: virtual ~Base () {} virtual bool operator==(const Base &) = 0; }; class MockBase: public Base { public: MOCK_METHOD1(Equals, bool(const Base &)); virtual bool oper...
6,492,668
6,492,716
assert, -NDEBUG and segmentation fault
I have quite a large piece of code, that works well in a development version, with many assert() in the code. I disabled assertions with -DNDEBUG directive passed to g++, and now my code breaks with seg. fault. Is there something I don't know about assert()?
The most common issue with assert to my knowledge is having code with side effects within the assert itself. When you compile with -DNDEBUG asserts are essentially commented out, and thus code inside the assert isn't executed. The assert man page mentions this in the bugs section: BUGS assert() is implemented...
6,492,844
6,492,896
List of primitive types for C++
Is there a function which would return (during compilation of metaprogram) in some form (List) a list of all available primitive types? Thanks
Incorrect question. What is list of types? std::list<T>? or array? If it is std::list then what is T? T = "std::string"? List of all types is described in C++ Standard. bool signed/unsigned char signed/unsigned short int signed/unsigned int signed/unsigned long size_t wchar_t float double
6,492,865
6,493,168
IWbemClassObject::Next yields VT_NULL types when they are not. What does this mean?
I'm using Microsoft WMI to connect to a WMI namespace for a third-party hardware API. All the initialization works fine. I get COM up and running, and I get connected to the WMI namespace. But when I call IWbemClassObject::Next to enumerate the class members, the members which are strings are returned as the type VT_NU...
Did you read the comment on the pVal parameter? The method calls VariantInit on this VARIANT, so the caller should ensure that the VARIANT is not active prior to the call. And did you read the remarks? If the underlying type of the property is an object path, date or time, or another special type, then t...
6,493,052
6,493,117
When inheriting from public interface, why it doesn't matter if the implementation is public or private?
I might be very well just tired or too long far from C++ but this one really surprised me today: #include <iostream> class Interface { public: virtual int aa() const = 0; virtual int bb() const = 0; }; class Usage : public Interface { private: virtual int aa() const { int a = 10 * 10; ...
This is specified in paragraph 11.6.1 of the standard: The access rules (clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [Example - basically same as yours] Access is checked at the call point using the type of th...
6,493,097
6,493,152
How can I print value of std::atomic<unsigned int>?
I am using std::atomic<unsigned int> in my program. How can I print its value using printf? It doesn't work if I just use %u. I know I can use std::cout, but my program is littered with printf calls and I don't want to replace each of them. Previously I was using unsigned int instead of std::atomic<unsigned int>, so I ...
template<typename BaseType> struct atomic { operator BaseType () const volatile; } Use a typecast to pull out the underlying value. printf("%u", unsigned(atomic_uint));
6,493,185
6,493,226
Cannot convert from 'int *' to 'int []'?
I know this might be a common question but I have tried to search but still cannot find a clear answer. I have the following code: int* f() { int a[] = {1,2,3}; return a; } int main() { int a[] = f(); // Error here getch(); return 0; } This code produces the error message: "Cannot convert from '...
There are actually two errors in this code. Firstly, you are returning the address of a temporary (the int array within f), so its contents are undefined after the function returns. Any attempt to access the memory pointed to by the returned pointer will cause undefined behaviour. Secondly, there is no implicit convers...
6,493,220
6,498,925
Get progress of SHA1 being computed using SHA1CryptoServiceProvider
Currently I am implementing into my C++/CLI code a function that return the SHA1 value of a file. It is a Windows Forms application in Visual Studio. I chose to implement the .NetFramework class SHA1CryptoServiceProvider because it is really fast (believe me). I have tested several algorithms but none of them were as f...
Finally I have done it. I post the code, maybe someone will find it useful. I know the code is not clean, I am still learning. It can compute SHA1 of files larger that 2^31 bytes. Tested it on a 22GB file. Works fine in backgroundWorker :) #define SHA1_BUFFER_SIZE 65535 //input buffer array<unsigned char,1>^ buf = gcn...
6,493,243
6,493,754
Creating Fancy dialog and window in C++
I wants to make a GUI application with some fancy graphics, like flipping the window, creating translucent window on window/Linux platform. What will be the steps for these, if I am using window/linux platform and C++ programming language using wxWidget or Juce. As I know idea how to create such window, But i have som...
On wxWidgets, I found an interesting message that states: Since wxFrame (which is usually the class you use for the main application), is derived from wxTopLevelWindow, you can use wxTopLevelWindow::SetTransparent(int alpha) method, where: an alpha value of 0 sets the window to be fully transparent, and a value of ...
6,493,260
6,493,360
C++ Print formatted data either to std::cout or to a file (buffered)
I have been using Petru's logging framework a bit. This is part of his code: class Output2FILE { public: static FILE*& Stream() { static FILE* pStream = stderr; return pStream; } }; Which is very nice as it simply logs to stderr without any action, but with the function that can afterwards be set to anythi...
You could use a pointer to an std::ostream much like the FILE* version. std::ostream* os = &std::cerr; if (log_to_file) { os = new std::ofstream("my.log"); } *os << "Hello Log!" << std::endl; if (log_to_file) { // or less 'safe' os != &std::cerr ... // close file here }
6,493,299
6,494,048
Will Visual C++ runtime malloc / free return memory to OS?
The question is a lot similar to Will malloc implementations return free-ed memory back to the system?, but I am interested about an answer for Windows / Microsoft Visual Studio, and about details on the exact virtual memory state. Will Visual C++ CRT free return the memory back to the system? What will be the exact st...
Inspecting the source code for 2010, it can be seen malloc/free call HeapAlloc/HeapFree Win32 API functions directly, with a _crtheap as a heap created by the runtime. The answer for VS 2010 and recent Windows versions (Win2000, WinXP, Vista, Win 7) therefore is: The memory returned by the free is returned to OS, but i...
6,493,687
6,525,748
Accessing elements of cvCreateMatND
I am new to OpenCV and I am trying to create a n-dimensional array and access each element using CvMatND. I can access a 2D matrix by data[i*step + j*nchannels + 0], how do I access the elements of a matrix created by int size[] = { 12, 12, 12 }; CvMatND* matB = cvCreateMatND(3, size, CV_8U); int *Da...
I've reviewed and tested my previous answer, and as you have found out it was not accurate. This is the working code to iterate on all the elements of a 3D array. int size[] = { 5, 5, 5 }; CvMatND* matA = cvCreateMatND(3, size, CV_32F); cvSetZero(matA); for (int x = 0; x < matA->dim[0].size; x++) { for (int y = 0;...
6,493,958
6,494,116
From where does the compiler start reading
This is a small program : #include <iostream> using namespace std; int main() { f(); system("pause"); } void f() { static int x = 20 ; class tester { public : tester() { cout << x ; } } x1; } The error that i get here is :error C3861: 'f': identifier not found If i...
The beginning of the compilation and the beginning of the execution of the program are two different things. The execution starts from the main. The compilation begins from the beginning of the file; the compiler don't "jump around" the file to find the needed pieces, but it reads the input in a linear fashion (I suspe...
6,494,101
6,494,173
Any issues with mixing libraries with and without std=c++0x
I am writing a library that must depend libraries that are not presently compiling with support for the new standard. I would like to compile a library which must depend on those libraries with std=c++0x. Are there any problems with doing this?
If you mix libraries compiled with different compiler options then you must ensure that the ABI for the data types in the interface is the same. Some data types (such as std::string) have different interfaces and requirements between C++03 and C++0x, so interfaces that use them must be careful. If your interfaces only ...
6,494,278
6,494,358
destructor does not work?
#include <iostream> using namespace std; class Tester { public: Tester(int x); ~Tester(); int who; } Tester_g_1(1) , Tester_g_2(2); Tester::Tester(int id) { cout << "Intializing" << id << endl ; who = id; } Tester::~Tester() { cout << "Destroying" << who << endl; } int main() { Tester localObj(3); cout << "This is...
localObj is destructed when the main terminates (because its it's scope), which happens after the system("pause"). You press a key, the destructor runs but immediately the window closes, so you don't see it. To see the text of the destructor, you have to run the program from the command line, or use the "Start program ...
6,494,454
6,495,338
class constructor disassembly
There is a small section of disassembly after the call to the constructor, that does not make any sense. Here it is, .text:011A18F0 loc_11A18F0: ; CODE XREF: main+5Bj .text:011A18F0 mov [ebp+again_obj], 0 .text:011A18FA .text:011A18FA loc_11A18FA: ...
var_4 is an internal variable (I'll call it '_state') which tracks the state of constructed objects for unwinding in case the exception happens. What you see is a common pattern made by VC++ when dealing with new'ed objects. E.g. A* pA1 = new A(); is converted to something like this: _state = -1; ... A *temp_pA1 = op...
6,494,530
6,494,568
Sockets in C++ and Java
I was wondering whether networking is easier in Java or C++. Because I know in Java networking with sockets and such is incredibly easy, such as doing the following: Socket s= new Socket(); s.connect(new SocketAddress("localhost",8888)); and if it is significantly harder in C++ that heavily influences my decision. Tha...
Building working socket code in Java is easier than in C++. Building "good" socket code in either depends more on the developer's experience and skill than on the language. C++ has Boost.Asio that makes this a bit easier.
6,494,591
6,495,205
How can I reliably get an object's address when operator& is overloaded?
Consider the following program: struct ghost { // ghosts like to pretend that they don't exist ghost* operator&() const volatile { return 0; } }; int main() { ghost clyde; ghost* clydes_address = &clyde; // darn; that's not clyde's address :'( } How do I get clyde's address? I'm looking for a solutio...
Update: in C++11, one may use std::addressof instead of boost::addressof. Let us first copy the code from Boost, minus the compiler work around bits: template<class T> struct addr_impl_ref { T & v_; inline addr_impl_ref( T & v ): v_( v ) {} inline operator T& () const { return v_; } private: addr_impl_ref & ...
6,494,594
6,494,744
parallel uniform distribution pseudorandom namber using OpenMP
i use in my program boost uniform distribution between 0 and 1: #include <boost/random/uniform_01.hpp> #include <boost/random.hpp> static boost::mt19937 rng; static boost::uniform_01<boost::mt19937&> zeroone(rng); zeroone() function is called inside a for-loop which i would like to parallel, using OpenMP. for ( ...
You can do what you suggest, but it would be insane...ly inefficient (because the purpose of a RNG is to generate hard-to-predict pseudo random sequences, the only way to .... predict the nth successor would be to generate the intervening ones as well.) most likely unnecessary: You can give each thread it's own priva...
6,494,974
6,495,064
Static builds with Qt creator
I am using Qt Creator with Qt 4.7.4 in the SDK given out by Nokia and wish to build an application with no .DLLs or other external libraries (just a standalone .exe) for Windows. How is this done (please give all possible details as I am new to this)? I understand one can build static apps using Qt only (not Qt creato...
/How-to-statically-link-qt-4/ link here will help you achieve, what you are trying to do. I am aware that answers in the form of embedded links is usually discouraged for the fact that if the source of the link goes down the answer becomes meaningless but in this case the content is too big & enriched to be reproduced...
6,495,619
6,932,709
How do I stop VS2K10 from caching environment variables
I'm in the middle of writing a C++ extension to a computer game using a third-party library. Since each person who develops against this system may have the header files in different directories, it uses environment variables in its project file to point to where those header files are located. Occasionally, new versi...
It turns out this may have been something with the way that Visual Studio or Windows was configured on that computer. My laptop's Visual Studio 2010 install does not exhibit this same problem. This machine had a critical existence failure late last week, and I'll see if its replacement has the same problem after I ins...
6,495,632
6,495,917
Mixing operator new[] and placement new with ordinary delete[]
Just out of curiosity, is the following legal? X* p = static_cast<X*>(operator new[](3 * sizeof(X))); new(p + 0) X(); new(p + 1) X(); new(p + 2) X(); delete[] p; // Am I allowed to use delete[] here? Or is it undefined behavior? Similarly: X* q = new X[3](); (q + 2)->~X(); (q + 1)->~X(); (q + 0)->~X(); operator de...
I'm pretty sure both give UB. §5.3.4/12 says the array form of a new expression may add some arbitrary amount of overhead to the amount of memory allocated. The array delete can/could then do something with the extra memory it expects to be there, but isn't since you didn't allocate the extra space it expects. At the ...
6,495,705
6,495,745
How to assign char* (with every possible value) to C++ string
I'm in C++. And I'm trying to append a char array to a C++ string. The only thing is that this array can have every possible value, negative, positive and 0. So when I assign this array to the string, it stops at some point because it found a 0 value. 1) Can string append these values? Or do they have to be strictly fr...
The string::append( const char* s, size_t n ) overload for append() should do what you want. Assuming that cpp_string is your std::string variable or reference and c_string_ptr is your pointer to an array of characters: cpp_string.append( c_string_ptr, number_of_bytes); Note however, the std::string is a typedef for ...
6,495,717
6,495,819
Index of closest points between two arrays
Given two vectors foo and bar, I want to output a vector of length foo.size() containing the index to the "closest" element of bar. I don't like reinventing the wheel - are there any STL algorithms or otherwise to do this concisely? #include <vector> #include <cmath> #include <float.h> int main() { vector<double> ...
This exact algorithm doesn't exist, but you could implement it in an idiomatic STL way by using std::min_element and a custom functor: template <typename T> T norm(const T& a, const T& b) { return abs(b - a); } template <typename T> struct closer_compare { closer_compare(const T& to) : to(to) {} bool opera...
6,495,778
6,495,950
Problems with overload function and luabind
I have a class that I want to bind to lua. The reduced code might be: class CSprite2D{ void setPosition(glm::ivec2 val) { m_position = val; } void setPosition(int posX, int posY) { m_position.x = posX; m_position.y = posY; } static void exposeAPI(lua_State* L,const unsigned char* data) { assert(...
You are casting the function to the wrong type, you need to cast to a pointer-to-member-function. Try: .def("setPosition", (void (CSprite2D::*)(int, int))&CSprite2D::setPosition)
6,495,908
6,495,951
Elegant porting of lambda expressions in C++
Since lambda expressions require GCC version > 4.4: what is the most elegant or fastest (yet not too 'dirty') way of porting code containing a couple of lambda expressions with reference-bound variables to pre-C++0x code? Can this be done in a semi automated way using templates/macros?
Maybe you should take a look at boost::lambda. This should do what you are looking for.
6,495,937
6,495,970
select derived class file global variable by base class virtual function
This is a common problem I am facing. I am intended to write a derived class for an existing code. Let me provide the code snippet (just example): Base_class_file: const int addr=0xA; Base_class::Read() { return *addr; } Please note, the addr variable is a global variable in base class file. Now, I am writing the d...
How about.... virtual int & GetTheGlobalVariable() const {return addr;} and then overriding that method in the subclass to return a different result?
6,495,965
6,496,871
Supporting both Tcl and Python?
I have a binary application that is statically linked against Tcl and the front end is the Tcl interpreter. I would like to offer users the capability of using Python to execute the same commands, as keyword options. A sample of the Tcl syntax is: set_foo -foo 1.0 -bar 3.0 -cat x so the python equivalent might look ...
Calling a Python interpreter from Tcl Needless overhead. However, Python's tkinter module calls Tcl from Python. There is a precedent, but it seems convoluted to introduce too many interface layers. Compiling separate applications for a Python front end and a Tcl front end. This is very common. Many projects hav...