question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,390,073
1,390,115
Variable-length objects: Ever a good idea?
My application uses a large amount of Panda objects. Each Panda has a list of Bamboo objects. This list does not change once the Panda is initialized (no Bamboo objects are added or removed). Currently, my class is implemented as follows: class Panda { int a; int b; int _bambooCount; Bamboo* _bamboo;...
C++ gives you another option. You should consider using std::vector. class Panda { int a; int b; std::vector<Bamboo> bamboo; // if you do not want to store by value: //std::vector< shared_ptr<Bamboo> > bamboo; Panda (int count, Bamboo* bamb) : bamboo( bamb, bamb+count ) {} } If you want to sto...
1,390,340
1,390,660
How can I use std::remove on a container with std::tr1::weak_ptr?
If I had a STL container, say a list of pointers I could remove them like in the exmple below. With a container of weak_ptrs this does not work, because they cannot be compared, as they need to be locked first. What can I do? void MyClass::RemoveItem(std::tr1::weak_ptr<Item> const & pItem) { mylist.remove(pItem); }...
For one thing, you could just define operator == for any weak_ptr. I'm sure there's a reason this is not implemented, it can probably bite you at a later point. template <typename T> bool operator == (const std::tr1::weak_ptr<T>& a, const std::tr1::weak_ptr<T>& b) { return a.lock() == b.lock(); } ... and you'll be...
1,390,401
1,390,438
Doing pointer math in a c++ class: Is it "legit"?
Ah-hoi, hoi, I'm wondering if it's ok to do something like the following: class SomeClass { int bar; }; SomeClass* foo = new SomeClass(); int offset = &(foo->bar) - foo; SomeClass* another = new SomeClass(); *(another+offset) = 3; // try to set bar to 3 Just Curious, Dan O
I suppose tecnically it might work out. However, there are several problems. bar is private. You are mixing pointers of different types (pointer arithmetic relies on the pointer type: int* + 1 and char* + 1 have different results because int and char have a different size). Have you also considered pointers to members:...
1,390,471
1,390,497
How to write a MultiPart download C++ program
I want to write a C++ program to download files with HTTP. For the sake of learning I would like to implement multipart downloading in my program the way DownThemAll! does. It is not possible to do lseek on a linux socket. I suppose it would be some HTTP option that we would need to specify, telling where to start down...
I suggest you take a look at section 14.35.1 Byte Ranges of the HTTP spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1,390,508
1,390,516
HTTP parsing library for linux C++
can anyone suggest a good HTTP parsing library for linux?
libcurl? It supports most web-based protocols, widely used, and stable. Available on most Linux distributions and should be around for Windows too. It supports both a simplified interface for quick-and-dirty implementations as well as an advanced interface for a robust implementation.
1,390,606
1,390,732
C++ static operator overloading
Is it possible to overload C++ class operators in the static context? e.g. class Class_1{ ... } int main() { Class_1[val]... }
If you are looking for metaprogramming using the built-in operator: Such a thing isn't possible - the built-in operators operate on runtime values, not on compile time values. You may use boost::mpl for that, and instead of using the built-in operators, use its templates, like at for op[], plus<a, b> for op+ etc. int...
1,390,703
1,391,479
Enumerate over an enum in C++
In C++, Is it possible to enumerate over an enum (either runtime or compile time (preferred)) and call functions/generate code for each iteration? Sample use case: enum abc { start a, b, c, end } for each (__enum__member__ in abc) { function_call(__enum__member__); } Plausible ...
To add to @StackedCrooked answer, you can overload operator++, operator-- and operator* and have iterator like functionality. enum Color { Color_Begin, Color_Red = Color_Begin, Color_Orange, Color_Yellow, Color_Green, Color_Blue, Color_Indigo, Color_Violet, Color_End }; namespace s...
1,390,913
1,390,922
Are static variables in a base class shared by all derived classes?
If I have something like class Base { static int staticVar; } class DerivedA : public Base {} class DerivedB : public Base {} Will both DerivedA and DerivedB share the same staticVar or will they each get their own? If I wanted them to each have their own, what would you recommend I do?
They will each share the same instance of staticVar. In order for each derived class to get their own static variable, you'll need to declare another static variable with a different name. You could then use a virtual pair of functions in your base class to get and set the value of the variable, and override that pair ...
1,390,991
1,391,277
Simulating static constructors in C++?
Is there anyway I can modify this code example #include <stdlib.h> #include <iostream> class Base { public: Base() { if(!m_initialized) { static_constructor(); m_initialized = true; } } protected: virtual void static_constructor() { std::cout << "Base::static...
I adopted this solution from the solution by Martin V Lowis. The main differences are that it uses multiple inheritance, and the CRTP: template<class T> class StaticInitializer : public T { static bool initialized; public: StaticInitializer(){ if(!initialized){ T::static_constructor(); initialized=...
1,391,227
1,391,264
What is a "set" in C++? When are they useful?
I'm having a hard time conceptualizing c++ sets, actually sets in general. What are they? How are they useful?
Don't feel bad if you have trouble understanding sets in general. Most of a degree in mathematics is spent coming to terms with set theory: http://en.wikipedia.org/wiki/Set_theory Think of a set as a collection of unique, unordered objects. In many ways it looks like a list: { 1, 2, 3, 4 } but order is unimportant: { 4...
1,391,304
1,391,320
Can I cast an array like this?
Example code: #include <cstdlib> #include <iostream> using namespace std; class A { public: A(int x, int y) : x(x), y(y) {} int x, y; }; class B { public: operator A() { return A(x,y); } float x, y; }; void func1(A a) { cout << "(" << a.x << "," << a.y << ")" << endl; } void func2(A ...
When you pass array to a method you are only passing the address of the first element not the actual copy of the array nor the first element. In func1 you pass first element of array which is object of class B. Because B has operator A() it can convert B to A and new object of class A is passed to func1 In func2 you pa...
1,391,426
1,391,430
Are member functions guaranteed to be ready before the creation of any object?
Consider this example: #include <iostream> class myclass { public: void print() { std::cout << "myclass"; } }; int main() { myclass* p = 0x0; // any address p->print(); // prints "myclass" } I didn't call the member function print through an object of type myclass. Instead I called it from a pointer to ...
Dereferencing a null (0) pointer is invoking undefined behaviour. The program can do anything it likes, including work as expected. In part, you get away with it here because the print() member function does not reference any member variables (there aren't any), but the compiler could still have generated code that wo...
1,391,504
1,430,020
deflateEnd error 'no msg' kind: 'Z_DATA_ERROR': -3
I have a program that links in zlib v1.2.3 and it got the following error: deflateEnd error 'no msg' kind: 'Z_DATA_ERROR': -3 The program has work successfully with lots of different files to be compressed. Does anyone know what the 'no msg' of kind Z_DATA_ERROR means and how one would go about debugging it?
This means that deflateEnd() was incorrectly called before deflate() had been called enough times to consume all the input or produce all the output. Solution is to figure out why the program did not keep calling deflate() sufficient times. In my case, it was a fencepost error and the final calls to deflate() that sp...
1,391,549
1,395,589
Good way to send result of 'uname -a' to a stream?
What is a good way to call 'uname -a' from a C++ program and send the results to a stream? I looked at system() and exec(), but they do not seem to give access to the stdout of the call. Thanks. -William
Why not just retrieve the strings directly from the struct utsname returned from the uname(2) system call found on most Unix/Unix-like platforms? No need to fork a "uname -a" process.
1,391,641
1,391,701
Why does read of /proc/cpuinfo seem to not advance file position?
I have the following code which ends up forever reading '/proc/cpuinfo' as it keeps getting the same result every read. Why doesn't the file pointer get advanced and reach eof ever? Seems this special file has different semantics. const int bufSize = 4096; char buf[bufSize + 1]; const string cpuInfo = "/proc/cp...
for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) { is wrong. You're using read as an initializer, so read is only being called once, not once per loop. After that, you're just looping forever printing it out (because nothing is changing nRead).
1,391,670
1,391,713
Named Pipe strategies with dynamic memory?
Hokay so I have an application where I need some IPC... I'm thinking named pipes are the way to go because they are so easy to use. Anyways, I have a question about how to handle dynamic memory using named pipes. Say I have a class such as this: class MyTestClass { public: MyTestClass() { _data = new int(4); } ...
Both named pipes and shared memory have similar issues: You need to serialize the contents of the structure into the on the sending side and deserialize the structure from the on the receiving side. The serialization process is essentially identical whether you're using named pipes or shared memory. For embedded poi...
1,391,708
1,391,725
Is compile-time "strlen()" effective?
Sometimes it is necessary to compare a string's length with a constant. For example: if ( line.length() > 2 ) { // Do something... } But I am trying to avoid using "magic" constants in code. Usually I use such code: if ( line.length() > strlen("[]") ) { // Do something... } It is more readable, but not effici...
The capability to inline a function call is both a compiler-specific optimization and a common behavior. That is, many compilers can do it, but they aren't required to.
1,391,737
1,391,792
Using inline assembly from c++
Just to experiment assembly in C++, I tried the following, which is causing the application to crash: int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { __asm { push 5000 call Sleep } ...
I just checked the assembly code in VC++ 6. You have to call the routine like this: call dword ptr [Sleep]
1,391,746
1,397,588
How to easily indent output to ofstream?
Is there an easy way to indent the output going to an ofstream object? I have a C++ character array that is null terminate and includes newlines. I'd like to output this to the stream but indent each line with two spaces. Is there an easy way to do this with the stream manipulators like you can change the base for i...
This is the perfect situation to use a facet. A custom version of the codecvt facet can be imbued onto a stream. So your usage would look like this: int main() { /* Imbue std::cout before it is used */ std::ios::sync_with_stdio(false); std::cout.imbue(std::locale(std::locale::classic(), new IndentFacet()));...
1,391,756
1,391,772
What are some small, fast and lightweight open source applications (µTorrent -esque)?
Possible duplicate What is the best open source example of a lightweight Windows Application? µTorrent is a small bit-torrent client, a really small one. It doesn't come with an installer, just a exe, you drop in your PATH somewhere. It's super lightweight and yet feature rich. Plus it is the work of one man. I...
I think you should take a look at Notepad++ if you want to see a feature-rich low-consumption of power software :)
1,391,869
1,392,016
Canny Edge Detector in C
I am looking for a bit of clarification on how the algorithms implemented in Canny edge detection - Wikipedia entry - work. It seems pretty straightforward to perform noise reduction using a 2D Gaussian filter, but I have heard that using two 1D filters - how is this accomplished? It's also simple to calculate the gr...
Gauss distribution: [constants are omitted for simplicity] g2d(x,y)=exp(-xx-yy)=exp(-x^2) * exp(-y^2)=g1d(x) * g1d(y) Thus is can be separated into multiplication of 1d-distributions. And thus filtration can be done first in x-direction (independently on each row) and then in y-direction (independently on each column) ...
1,392,195
1,392,222
How to get event when application is closed from task manager?
I have developed a Win32 application using C/C++, which runs on Vista and XP. I wanted to know, can I get any event in my application when my application is killed from task manager, by selecting the "end process" button? I want to free some memory on exit of my application.
Nope, your application is terminated without any notice. You are at mercy of Task Manager.
1,392,200
1,392,228
Sizeof string literal
The following code #include <iostream> using namespace std; int main() { const char* const foo = "f"; const char bar[] = "b"; cout << "sizeof(string literal) = " << sizeof( "f" ) << endl; cout << "sizeof(const char* const) = " << sizeof( foo ) << endl; cout << "sizeof(const char[]) = " << sizeo...
sizeof("f") must return 2, one for the 'f' and one for the terminating '\0'. sizeof(foo) returns 4 on a 32-bit machine and 8 on a 64-bit machine because foo is a pointer. sizeof(bar) returns 2 because bar is an array of two characters, the 'b' and the terminating '\0'. The string literal has the type 'array of size N...
1,392,305
1,392,361
MSTest for huge legacy codebase
we have a huge codebase with about 1000k lines of native/unmanaged legacy c++ - code and we are going to provide the code with unit tests and MSTest would fit perfectly in our current development environment (TFS, VS 2010, ...). I know that MSTest is orginally meant to test managed code but its also possible to write u...
I would not recommend MSTest for managed testing. See here for my experiences. However if you do insist I would say a really good way to test you legacy code would be use PInvoke interop to your c++ code.
1,392,315
1,392,387
Problems with Singleton Pattern
I've been reading about Singleton pattern for last few days. The general perception is that the scenarios where it is required are quite few (if not rare) probably because it has its own set of problems such as In a garbage collection environment it can be an issue with regards to memory management. In a multithreaded...
In a garbage collection environment it can be an issue with regards to memory management In typical singleton implementations, once you create the singleton you can never destroy it. This non-destructive nature is sometimes acceptable when the singleton is small. However, if the singleton is massive, then you are unnec...
1,392,422
1,392,684
Problems with bit-shifting in complicated expressions
I've distilled an equation down to this: speed = ( ( rear_wheel_speed_a + front_wheel_speed_a ) << 10 ) + ( ( rear_wheel_speed_b + front_wheel_speed_b ) << 2 ); but for some reason I'm getting unexpected results so I must be doing something wrong. This started out like this: speed = ((((rear_wheel_speed_a * 25...
From the second formula, I assume you operating 2 16bit values separated into their 8bit part a and b: rear_wheel_speed = 0x0302 front_wheel_speed = 0x6fe2 and the formula you using, can be simplified into speed=(front_speed+rear_speed)*4. From your values, 0x6fe2*4 just can fit 16bit, so this value can be evaluated i...
1,392,494
1,403,236
Qt4 DNS Proxy QUdpSocket
I'm essentially trying to make a DNS proxy application using Qt4. If I set my DNS nameserver to 'localhost' then I want to forward all DNS requests to the server specified in the remoteSocket object. Everything seems to be working fine except sending the data from the remoteSocket object back to the localSocket objec...
I was assuming that using QUdpSocket::bind(), the resulting socket object would be able to obtain the peerAddress/peerPort using the access methods, however that was not the case. The final solution was to do: QHostAddress sender; quint16 senderPort; localSocket->readDatagram(localDatagram->data(), localDatagram->size...
1,392,820
1,393,217
Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?
I'm well aware that in C++ int someValue = i++; array[i++] = otherValue; has different effect compared to int someValue = ++i; array[++i] = otherValue; but every once in a while I see statements with prefix increment in for-loops or just by their own: for( int i = 0; i < count; ++i ) { //do stuff } or for( int...
If we ignore force of habit, '++i' is a simpler operation conceptually: It simply adds one to the value of i, and then uses it. i++ on the other hand, is "take the original value of i, store it as a temporary, add one to i, and then return the temporary". It requires us to keep the old value around even after i has bee...
1,392,863
1,420,261
Initializing qt resources embedded in static library
I have next situation: I need to create widget in standalone static library, which then will be linked with final application (visual c++ 9.0, qt 4.5). This static widget library contains some resources (icons), and consist of a several .cpp files (each contains standalone widget). As far as I know, i must initialize q...
It didn't work because you managed to get hit by static initialization order fiasco. You can't move your code that initializes static objects outsize the translation unit (you can read it as source file) where these static objects are used. Not the way you did it. If you want to use the scheme you are using to initia...
1,393,006
1,396,629
How to get the cpu usage per thread on windows (win32)
Looking for Win32 API functions, C++ or Delphi sample code that tells me the CPU usage (percent and/or total CPU time) of a thread (not the total for a process). I have the thread ID. I know that Sysinternals Process Explorer can display this information, but I need this information inside my program.
With the help of RRUZ's answer above I finally came up with this code for Borland Delphi: const THREAD_TERMINATE = $0001; THREAD_SUSPEND_RESUME = $0002; THREAD_GET_CONTEXT = $0008; THREAD_SET_CONTEXT = $0010; THREAD_SET_INFORMATION = $0020; TH...
1,393,065
1,394,257
Can I prevent invoking destructor before overloaded delete?
I'd like to use boost.pool. It's okay if you don't know about it. Basically, it has two main functions, malloc() and free(). I've overloaded new and delete for my custom defined class test. class test { public: test() { cout << "ctor" << endl; } ~test() { cout << "dtor" << en...
Can't reproduce, when added #include <iostream> #include <boost/pool/pool.hpp> using namespace std; (why do people omit such things that are necessary to make the code compile?!) and int main() { test* p = new test; delete p; } This is either a stripped-down and modified version that doesn't have that behavio...
1,393,074
1,393,184
Why people think that the only man who created C++ was Bjarne Stroustrup?
I am currently reading Stroustrup's book "Design and Evolution of C++" and it turns out that he was not the one who developed C++. When I hear someone saying "Bjarne Stroustrup developed C++ blah-blah-blah", I always feel it is very unfair to these guys who worked with BS - I mean Jonathan Shopiro, Andrew Koenig, Stan ...
C++ has gone through two major stages of its evolution. The early days were Bjarne Stroustrup making a language. He obviously borrowed ideas from others, and solicited feedback from several clever language designers, and no doubt had a small team working under him, but the language was fundamentally his baby. In those ...
1,393,454
1,393,547
Initialising an anonymous mutex-lock-holding class instance in the LHS of a comma operator
Suppose I have code something like this: #include "boost/thread/mutex.hpp" using boost::mutex; typedef mutex::scoped_lock lock; mutex mut1, mut2; void Func() { // ... } void test_raiicomma_1() { lock mut1_lock(mut1); Func(); } void test_raiicomma_2() { (lock(mut1)), Func(); } void test_raiicomma_3() { (lock(...
Is it correct that the temporary object destructor will not be called until the end of the expression, after Func() has returned? It is guaranteed that both constructor and destructor are called, as they have side effects, and that destruction will only happen at the end of a full expression. I believe it should wor...
1,393,507
1,394,538
scope vs ctags in terms of features
I am a big fan of ctags Hence I am wondering if I have cscope, will I benefit more there two programs. Seems like the latter has the same features as ctags, namely, facilitating the finding of symbols. What are the features scope offers that can further increase my productivity with VIM? Thanks
cscope can certainly improve your productivity. ctags only allows you to navigate to the declaration of a symbol (one-way lookup). cscope allows you to: Go to the declaration of a symbol Show a selectable list of all references to a symbol Search for any global definition Functions called by a function Functions calli...
1,393,564
1,393,641
Get owner's access permissions using C++ and stat
How can I get the file owner's access permissions using stat from sys/stat.h using C++ in Kubuntu Linux? Currently, I get the type of file like this: struct stat results; stat(filename, &results); cout << "File type: "; if (S_ISDIR(results.st_mode)) cout << "Directory"; else if (S_ISREG(results.st_mod...
struct stat results; stat(filename, &results); cout << "Permissions: "; if (results.st_mode & S_IRUSR) cout << "Read permission "; if (results.st_mode & S_IWUSR) cout << "Write permission "; if (results.st_mode & S_IXUSR) cout << "Exec permission"; cout << endl;
1,393,816
1,393,830
is it reasonable to program an algorithm without function calls?
I am programming an algorithm for a library and I didn't use function calls at all. The algorithm is about 100 lines and there is no duplicate code.or should I use inlining?
Is your algorithm readable? Maybe dividing it into several functions would be beneficial for readability (and hence maintainability) even if it will not reduce duplication.
1,393,898
1,395,340
How to add spin control to the dialog box using win32 C?
just want to know how to add an spin control ( in another name, up/down control ) in the dialog box using C program (win32 / code::block / mingw compiler)
Simplest way is by using a resource editor to design your dialog. Code::Blocks doesn't come with one, but ResEdit is one I've used. If you are editing an .rc file by hand, you'd add a line similar to the following within the dialog definition section: CONTROL "", IDC_SPIN1, UPDOWN_CLASS, UDS_ARROWKEYS, 7, 22, 1...
1,393,903
1,393,918
Why were references added to C++? (from the history viewpoint)
I've read many discussions on the difference between references and pointers and when to use which. They all seem to get their conclusions from analysis of the behaviors of the two. But I'd still like to know what was in the language designers' mind. What's the main motive for this design? In what typical situation is ...
Here's Stroustrup's reasons for adding them to the language. Basically they were mainly added to support operator overloading.
1,394,053
1,394,122
How to write a generic alert message using win32?
I just want to expand this following method into something more generic, which should accept any kind of argument and display it using MessageBox(): void alert(char *item) { MessageBox(NULL, item, "Message", MB_OK | MB_ICONINFORMATION); } Can anyone help?
#include <sstream> template<typename T> void alert(T item) { //this accepts all types that supports operator << std::ostringstream os; os << item; MessageBoxA(NULL, os.str().c_str(), "Message", MB_OK | MB_ICONINFORMATION); } //now you need specialization for wide char void alert(const wchar_t* item) { Messa...
1,394,132
7,166,199
macro and member function conflict
I have problem that,std::numeric_limits::min() conflicts with the "min" macro defined in "windef.h". Is there any way to resolve this conflict without undefine the "min" macro. The link below gives some hints, however I couldn't manage to use parenthesis with a static member function. What are some tricks I can use wi...
The workaround is to use the parenthesis: int max = (std::numeric_limits<int>::max)(); It allows you to include the windef.h, doesn't require you to #undef max (which may have adverse side effects) and there is no need to #define NOMINMAX. Works like a charm!
1,394,229
1,394,287
Understanding return value optimization and returning temporaries - C++
Please consider the three functions. std::string get_a_string() { return "hello"; } std::string get_a_string1() { return std::string("hello"); } std::string get_a_string2() { std::string str("hello"); return str; } Will RVO be applied in all the three cases? Is it OK to return a temporary like in t...
In two first cases RVO optimization will take place. RVO is old feature and most compilers supports it. The last case is so called NRVO (Named RVO). That's relatively new feature of C++. Standard allows, but doesn't require implementation of NRVO (as well as RVO), but some compilers supports it. You could read more abo...
1,394,370
1,394,398
What GNU make substitute do you recommend?
Imagine you're free to choose a tool like GNU make for a new C++ project. What would you choose? Are any usable substitutes out there? It shall have/be a command line interface "easy" to understand easy to set up for a default c++ project may support src/bin seperation as common for Java may not add too much dependenc...
I use cmake, and I'm very glad I made the switch. EDIT Feature list as found in the wikipedia article: Configuration files are CMake scripts, which use a programming language specialized to software builds Automatic dependency analysis built-in for C, C++, Fortran and Java Support of SWIG, Qt, via the CMake scripti...
1,394,910
1,394,929
How to tame the Windows headers (useful defines)?
In one of the answers to this question jalf spoke about useful define NOMINMAX, that could prevent from unwanted defining min/max macros. Are there other useful defines that can help to control windows.h (or other Windows headers, for instance Microsoft C Runtime headers or STL implementation) behavior?
The most commonly used is probably WIN32_LEAN_AND_MEAN - it disables rarely used parts of the API. You can find more on MSDN's Using the Windows Headers. I remembered wrong about MSDN listing those defines, so here's list from windows.h: /* If defined, the following flags inhibit definition * of the indicated ite...
1,394,912
1,394,924
Slot seemingly not recognized in Qt app
I have been working on learning C++ and Qt4 recently, but I have hit a stumbling block. I have the following class and implementation: class Window : public QWidget { public: Window(); public slots: void run(); private: //... }; and Window::Window() { //... connect(runBtn,SIGNAL(clicked()),this,...
Possibly you have forgotten a Q_OBJECT macro in your Window class? class Window : public QWidget { Q_OBJECT public: Window() ...
1,395,004
1,395,051
Simple assembly questions
; int __stdcall wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd) _wWinMain@16 proc near var_4= dword ptr -4 hInstance= dword ptr 4 hPrevInstance= dword ptr 8 lpCmdLine= dword ptr 0Ch nShowCmd= dword ptr 10h From what I can see, the last 4 variables are the parameters passed t...
a. DWORD is unsigned, 32 bit: see here (old name, MS started using it back when Windows was 16-bit). b. the top of stack (dword ptr 0) is taken up by the return-address c. a variable y here would not work. Anyway, this systematic use of dword ptr is characteristic of certain assemblers and disassemblers, not a "standar...
1,395,202
1,395,287
Overriding "new" and Logging data about the caller
I'm trying to write a memory profiler and so far have been able to get my custom functions to work for malloc, free, new and delete. I tried using __FILE__ and __LINE__ to log the originator inside the overloaded new method, but (as expected) it just gives the details of where the overloaded function is. Is there a way...
You can write new(foo, bar) MyClass; In this case the following function is called void*operator new(std::size_t, Foo, Bar){ ... } You can now call new(__LINE__, __FILE__) MyClass; and use the data with void*operator new(std::size_t, unsigned line, const char*file){ ... } Adding a macro #define new new(__LI...
1,395,361
1,395,398
manipulating LARGE_INTEGERS
I am converting some code from C to C++ in MS dev studio under win32. In the old code I was doing some high speed timings using QueryPerformanceCounter() and did a few manipulations on the __int64 values obtained, in particular a minus and a divide. But now under C++ I am forced to use LARGE_INTEGER because that's what...
LARGE_INTEGER is a union of a 64-bit integer and a pair of 32-bit integers. If you want to perform 64-bit arithmetic on one you need to select the 64-bit int from inside the union. LARGE_INTEGER a = { 0 }; LARGE_INTEGER b = { 0 }; __int64 c = a.QuadPart - b.QuadPart;
1,395,395
1,395,422
Arrays inside structs in C
I´m struggling to understand this concept: I have a fixed size definition: (from http://msdn.microsoft.com/pt-br/library/aa931918.aspx) typedef struct _FlashRegion { REGION_TYPE regionType; DWORD dwStartPhysBlock; DWORD dwNumPhysBlocks; DWORD dwNumLogicalBlocks; DWORD dwSectorsPerBlock; DWORD dwBytesPerBloc...
The concept is while FlashRegion looks like a fixed size structure, it is actually dynamically sized. The magic is done when allocating the structure - instead of calling (FlashRegion*)malloc(sizeof(FlashInfoEx)) or new FlashRegion, you call something like (FlashRegion*)malloc(sizeof(FlashInfoEx)+sizeof(FlashRegion)*(n...
1,395,396
1,395,460
error using restrict keyword
In the following example: void foo (double *ptr) { const double * restrict const restr_ptr=ptr; } I get this error: error: expected a ";" const double * restrict const restr_ptr=ptr; ^ I compile with -std=c99, using gcc 3.4 Any Ideas?
In C++, restrict is not a keyword (except for Microsoft extensions). It doesn't mean what it does in C. It looks as though you tried to apply C99 mode to your C++ compiler. Use a C compiler to compile C code, and use a C++ compiler to compile C++. Neither language is a subset of the other.
1,395,506
1,395,509
In c++ what does a tilde "~" before a function name signify?
template <class T> class Stack { public: Stack(int = 10) ; ~Stack() { delete [] stackPtr ; } //<--- What does the "~" signify? int push(const T&); int pop(T&) ; int isEmpty()const { return top == -1 ; } int isFull() const { return top == size - 1 ; } private: int size ; int...
It's the destructor, it destroys the instance, frees up memory, etc. etc. Here's a description from ibm.com: Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out...
1,395,601
1,395,727
What's the -complete- list of kinds of automatic type conversions a C++ compiler will do for a function argument?
Given a C++ function f(X x) where x is a variable of type X, and a variable y of type Y, what are all the automatic/implicit conversions the C++ compiler will perform on y so that the statement "f(y);" is legal code (no errors, no warnings)? For example: Pass Derived& to function taking Base& - ok Pass Base& to functio...
Note how the built-in types have some quirks compared to classes: a Derived can be passed to function taking a Base (although it gets sliced), and an int can be passed to function taking a long, but you cannot pass an int& to a function taking a long&!! That's not a quirk of built-in vs. class types. It's...
1,395,715
1,395,988
Should const functionality be expanded?
EDIT: this question could probably use a more apropos title. Feel free to suggest one in the comments. In using C++ with a large class set I once came upon a situation where const became a hassle, not because of its functionality, but because it's got a very simplistic definition. Its applicability to an integer or s...
Scott Meyers was working on a system of expanding the language with arbitary constraints (using templates). So you could say a function/method was Verified,ThreadSafe (etc or any other constraints you liked). Then such constrained functions could only call other functions which had at least (or more) constraints. (eg a...
1,396,050
1,396,169
use gtk_signal_connect with a member function in c++
What's the best way to connect a GTK+ signal to a non-static member function? I have a GUI class in c++ that uses gtk, and i want do something like this: Gui::Gui () { gtk_signal_connect(GTK_OBJECT(somObject), "clicked", GTK_SIGNAL_FUNC( &(this->ClickHandler) ), ...
I assume your class contains some internal data that the signal handler needs access to. If not, just use a static function for the signal handler. Otherwise, here are a couple of ideas: Create a sigc++ or boost functor out of the member function; set it as the data passed to the signal handler. Use a generic signa...
1,396,107
1,397,356
C++: Status and control pattern
I'm writing a C++ background/server application for Linux/Windows. Is there a standard control/profiling/reporting service I should use to expose my application's current status in a standardized way? If not, what's a good pattern (or library) to use for exposing this kind of data and control? Specifically, I want to ...
Many Linux systems now have dbus for this sort of stuff. Daemons run and provide information and a control interface on the system bus. Desktop applications communicate with one another via the session bus. For instance, the bluez bluetoothd daemon uses dbus to provide information about bluetooth devices and services, ...
1,396,265
1,396,331
Defining a variable inside c++ inline assembly
Let's say we have the following c++ code: int var1; __asm { mov var1, 2; } Now, what I'd like to know is if I didn't want to define var1 outside the __asm directive, what would I have to do to put it inside it. Is it even possible? Thanks
To do that, you'll need to create a "naked" method with _declspec(naked) and to write yourself the prolog and the epilog that are normally created by the compiler. The aim of a prolog is to: set up EBP and ESP reserve space on stack for local variables save registers that should be modified in the body of the function...
1,396,267
1,407,137
OleInitialize fails when Common Lanuage Runtime is enabled?
I am working on a wxWidgets console application that I want to call into = a C# DLL from, via the CLR. Unfortunately, the application hiccups in the wxWidgets application initialization code because OleInitialize is failing. The error I'm seeing is a pop-up simply stating "Cannot initialize OLE." It seems that this p...
As mentioned in my question, this is a problem involving the thread style settings between the C++ application and the CLR defaults. This was apparently a bug, once upon a time, and Microsoft has released a fix: http://msdn.microsoft.com/en-us/library/s6bz81ya.aspx Recompiling the executable the uses the CLR-enabled ....
1,396,340
1,396,344
What does the "|" in "int style = SWT.APPLICATION_MODAL | SWT.OK;" do (and how to Google it)?
I can't search for | in Google. If you had found it in a software source code that you are trying to interpret, you didn't know what it does and you couldn't ask other people for help, how would you find out what it does?
The pipe operator in this case means "use both SWT.APPLICATION_MODAL and SWT.OK as options/flags for my popup box." It's a very commonly used idiom with bitfield configuration identifiers, esp. in windowing systems like SWT or Win32. How it works The pipe (|) operator is the bitwise OR operator, that is, it computes a...
1,396,397
1,396,595
Build Boost-powered solution in VS
Boost rocks, it is great and extremely powerful, but I hate it everytime I build solution in my Visual Studio 7.1. It seems Boost has impact on build time (not positive). I cannot remove all Boost usage from my project to compare build times but I tried it on small projects and the difference is meaningful. I guess t...
Naturally, including boost leads to longer compilations times - just like including any library does. Being (mostly) a template library offcourse leads to quite big performance penalty as all of the logic is implemented in the headers. I've had good results including (a subset of) boost in precompiled headers. However...
1,396,458
1,402,325
Confusing function lookup with templates in C++
Starting with the following (using gcc version 4.0.1): namespace name { template <typename T> void foo(const T& t) { bar(t); } template <typename T> void bar(const T& t) { baz(t); } void baz(int) { std::cout << "baz(int)\n"; } } If I add (in the global namespace) struct test...
I assume you added the double version to the global namespace too, and you call foo from main after everything is defined. So this is basically two phase name lookup. Looking up an unqualified function name that is dependent because an argument in the call is dependent (on its type) is done in two phases. The first p...
1,396,691
1,396,733
Programmatically get amount of RAM installed on OS X
I'm working on a machine that has 8 gigs of memory installed and I'm trying to programmatically determine how much memory is installed in the machine. I've already attempted using sysctlbyname() to get the amount of memory installed, however it seems to be limited to returning a signed 32 bit integer. uint64_t total =...
You can use sysctl() and query HW_MEMSIZE.This returns the memory size as a 64-bit integer, instead of the default 32-bit integer. The man page gives the details.
1,396,942
1,396,988
Efficient computation of the high order bits of a 32 bit integer multiplication
Many CPUs have single assembly opcodes for returning the high order bits of a 32 bit integer multiplication. Normally multiplying two 32 bit integers produces a 64 bit result, but this is truncated to the low 32 bits if you store it in a 32 bit integer. For example, on PowerPC, the mulhw opcode returns the high 32 bits...
gcc 4.3.2, with -O1 optimisation or higher, translated your function exactly as you showed it to IA32 assembly like this: umulhi32: pushl %ebp movl %esp, %ebp movl 12(%ebp), %eax mull 8(%ebp) movl %edx, %eax popl %ebp ret Which is just doing a si...
1,397,004
1,397,017
Better seeds than time(0)?
I understand that time(0) is commonly using for seeding random number generators and that it only becomes a problem when the program is being run more than once per second. I'm wondering what are some better seeds to consider when generating random numbers. I read about GetTickCount, timeGetTime, and QueryPerformanceCo...
Some early hacks of Netscape security centered around knowing when an encrypted packet was sent and narrowing down the possible range of seeds with that knowledge. So, getting a tick count or something else even remotely deterministic is not your best bet. Even using a seed, the sequence of "random" numbers is determi...
1,397,110
1,401,069
How to overload operators with Boost.Python
I am trying to overload operators of a C++ class using Boost.Python. According to this, I am doing it the right way... but I have a bunch of compiler errors. Here is a simple example I made trying to pinpoint the problem: #include "boost/python.hpp" using namespace boost::python; class number { public: number(int...
I've not used boost.python, but your errors look like there are some incompatible arguments when some template magic tries to bind something to something else. So I looked at the link you provided, and found one major difference: class_<X>("X") .def(self + int()) vs yours class_<number>("number", init<int>()) ...
1,397,190
1,397,219
Visual C++ Precompiled Headers errors
Update: What are the effects of including stdafx.h in my header files? I started on a C++ project in Linux/Eclipse CDT and imported it into Visual C++/Windows. In Visual C++, I started using precompiled headers to speed up compilation and defined stdafx.cpp and stdafx.h. Here's my stdafx.h #pragma once #include <st...
You put "create precompiled header" only for stdafx.cpp. Then "use precompiled header" for all of the other ".cpp" files. Finally, have include "stdafx.h" at the start of each ".cpp" file (not usually in the header files.
1,397,313
1,397,343
Programmatically get Google search results
How can I get Google search results from inside a program? I need to get an array of search results for a specified string.
C++ requires a little more work then other languages. You will need to connect to Google's REST Search API and then use a JSON parser to parse out the search results. Json.org has a collection of JSON parsers in various languages.
1,397,484
1,401,533
Custom text color for certain indexes in QTreeView
I would like to draw texts in one of the columns in a QTreeView widget using a custom color (depending on the data related to each row). I tried to overload the drawRow() protected method and change the style option parameter like this (a stripped-down example): virtual void drawRow(QPainter* p_painter, const QStyleOpt...
In your model, extend the data() function to return a given color as the Qt::ForegroundRole role. For example: virtual QVariant MyModel::data( const QModelIndex &index, int role ) const { if ( index.isValid() && role == Qt::ForegroundRole ) { if ( index.column() == 2 ) { return QVari...
1,397,490
1,397,508
Implementing std::list item read/write events
I'm new to c++ but have set my mind on a specific task that needs me to enable adding a specific chunk of code to be execute whenever any list item is attempted to be changed or read. The resulting list should behave and look as much as as possible to std::list except for this small exception that would enable me to ex...
Deriving from std::list is almost certainly not the answer. The collections in stl are simply not meant to be derived from and doing so will cause you problems down the road. The classic example of why is the destructor problem. The destructors in stl collections are not virtual. This will break any logic you place...
1,397,678
1,397,689
C pointer array scope and function calls
I have this situation: { float foo[10]; for (int i = 0; i < 10; i++) { foo[i] = 1.0f; } object.function1(foo); // stores the float pointer to a const void* member of object } object.function2(); // uses the stored void pointer Are the contents of the float pointer unknown in the second functio...
For the first question, yes using foo once it goes out of scope is incorrect. I'm not sure if it's defined behavior in the spec or not but it's definitely incorrect to do so. Best case scenario is that your program will immediately crash. As for the second question, why does making it const work? This is an artifa...
1,397,737
1,397,766
How to get the digits of a number without converting it to a string/ char array?
How do I get what the digits of a number are in C++ without converting it to strings or character arrays?
The following prints the digits in order of ascending significance (i.e. units, then tens, etc.): do { int digit = n % 10; putchar('0' + digit); n /= 10; } while (n > 0);
1,397,862
1,398,063
is there any database transaction mechanism in MFC/C++?
I want to make sure that if any error occurs during the database processing phase, program will know it need to roll back the whole process. any good ORM in MFC/C++ for doing this ?
The MFC _ConnectionPtr object has BeginTrans, CommitTrans and RollbackTrans methods. http://msdn.microsoft.com/en-us/library/ms675942(VS.85).aspx I wouldn't call it good though, you'd need to wrap it.
1,397,924
1,398,378
Get original SQL query from prepared statement in SQLite
I'm using SQLite (3.6.4) from a C++ application (using the standard C api). My question is: once a query has been prepared, using sqlite3_prepare_v2(), and bound with parameters using sqlite3_bind_xyz() - is there any way to get a string containing the original SQL query? The reason is when something goes wrong, I'd li...
As per the comments in sqlite3.c (amalgamation), sqlite3_sql(myQuery) will return the original SQL text. I don't see any function for finding the value bound at a particular index, but we can easily add one to the standard set of SQLite functions. It may look something like this: const char* sqlite3_bound_value(sqlite3...
1,398,234
1,398,282
How to save and load a C++ application state in a modular way
I have a distributed C++ application, which is composed of 4 processes spread on 2 machines. One of the applications serves as "control center" for the rest of the applications. I want to be able to save the current state to a file and load it again later. What exactly is a "state" is defined separately by each module...
Have a look at the boost.Serialize lib. It's a very nice lib for (un)streaming objects to an (xml) file. Instead of writing a Load and Save function your class only need to write a serialize function and this function will work both ways. class X { friend class boost::serialization::access; template<class Archiv...
1,398,274
1,398,374
How to reconstruct a data-structure from injected process' memory space?
I've got this DLL I made. It's injected to another process. Inside the other process, I do a search from it's memory space with the following function: void MyDump(const void *m, unsigned int n) { const char *p = reinterpret_cast(m); for (unsigned int i = 0; i < n; ++i) { // Do somethi...
If your victim is written in C or C++, and the datatypes used are truly that simple, then you'll always find them as a single block of bytes in memory. But as soon as you have C++ types like std::string that observation no longer holds. For starters, the exact layout will differ between C++ compilers, and even differe...
1,398,331
1,398,366
How do I implement a "single instance"-like design?
I'm writing an application which will run as a daemon. UIs will connect to it over TCP. Now, there is a class called UiTcpInterface which will handle all communication between the UI and this daemon. Now, I'm faced with the problem of ensuring there is only one instance of UiTcpInterface. What would be the best way to ...
This has been discussed many, many times. Singleton - Why use classes? Problems with Singleton Pattern Why choose a static class over a singleton implementation? https://stackoverflow.com/questions/1304647/static-storage-vs-singleton-why-people-prefer-singleton-closed
1,398,436
1,398,525
C++ interview - testing potential candidates
I have to interview some C++ candidates over the next few weeks and as the most senior programmer in the company I'm expected to try and figure out whether these people know what they are doing. So has anybody got any suggestions? Personally I hate being left in a room to fill out some C++ questions so I'd rather do a ...
I wouldn't make them write code. Instead, I'd give them a couple of code snippets to review. For example, the first would be about design by contract: See if they know what preconditions, postconditions and invariants are. Do a couple of small mistakes, such as never initializing an integer field but asserting that it ...
1,398,445
1,398,594
Directory structure for a C++ library
I am working on a C++ library. Ultimately, I would like to make it publicly available for multiple platforms (Linux and Windows at least), along with some examples and Python bindings. Work is progressing nicely, but at the moment the project is quite messy, built solely in and for Visual C++ and not multi-platform at ...
One thing that's very common among Unix libraries is that they are organized such that: ./ Makefile and configure scripts. ./src General sources ./include Header files that expose the public interface and are to be installed ./lib Library build directory ./bin Tools build directory ./tools To...
1,398,763
1,399,160
Delphi PChar to C++ const char*
I am trying to use a C++ dll from a native program. I am following the virtual method scenario as explained here Lets say my C++ function signature is of the form int Setup(const char* szIp, const char* szPort); And the corresponding delphi signature is function Setup(ip, port: PChar):Integer: virtual; cdecl; abstrac...
In Delphi 2010 (and Delphi 2009) the "char" type is actually a WIDEChar - that is, 16 bits wide. So when you call your C++ function, if that is expecting CHAR to be 8 bits wide (so called "ANSI", rather than UNICODE), then it is going to misinterpret the input parameter. e.g. if you pass the string 'ABC'#0 (I'm showin...
1,398,837
1,399,619
Programmatically launch sfx archive on Windows 7 (using _execv)? (C++)
My (MS Windows) application can update itself over the internet by download a self extracting archive and launching it via _execv (C++). Now while launching the sfx archive works fine on Windows XP, it doesn't on Windows 7. I guess it has to do with UAC, but even turning UAC off didn't cure this problem. The downloaded...
Windows 7 is able to detect installers based on file name and file content and requires additional privilege to start such files. As far as I know Administrator has no such additional privilege. Try to use ShellExecuteEx with runas parameter. It should show you dialog with request for permission to start installer.
1,398,843
1,561,223
Service Control Security Issues in XPCOM
I'm am developing a Firefox extension which interfaces with an underlying Windows service (which I have already made). During the development so far I encountered one bug in the installer program (which installs the FF extension AND the service). This was due to the security model on Vista requiring elevated privileges...
Yes, if your service is running as an Administrator then the Firefox process, running as a normal user will not be able to start or stop it. However, it appears that you can use the "sc" command to set access controls on your service from your installer, which means you can allow non-admin users to start and stop your ...
1,398,855
1,398,877
Which one will be faster
Just calculating sum of two arrays with slight modification in code int main() { int a[10000]={0}; //initialize something int b[10000]={0}; //initialize something int sumA=0, sumB=0; for(int i=0; i<10000; i++) { sumA += a[i]; sumB += b[i]; } printf("%d %d",sumA,su...
There is only one way to know, and that is to test and measure. You need to work out where your bottleneck is (cpu, memory bandwidth etc). The size of the data in your array (int's in your example) would affect the result, as this would have an impact into the use of the processor cache. Often, you will find example 2 ...
1,399,051
1,399,120
WNDPROC declaration problem, converting from C to C++
I am converting a program from C to C++. I have the compiler set to use the __fastcall calling convention by default. I used to have a declaration line as follows: INT32 PASCAL graph_window_handler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) Later I have: wndclass.lpfnWndProc = graph_window_handler; Thi...
According to MSDN documentation it should look like the following: LRESULT CALLBACK graph_window_handler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); And if you'll check WinUser.h you'll see that WNDPROC typedef'ed as follows: typedef LRESULT (CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM);
1,399,062
1,400,034
Making my GUI accessible through keyboard (Xp, Visual Studio, C++)
I've built a GUI with button, groups of buttons, edits, listboxes... etc... but now I want to know how to make my gui accessible through keyboard, I mean, changing the focus by pressing tab button. Does anybody have any idea on how to do this? I'm using Windows Xp and the GUI is writen on C++ using Visual Studio 2008. ...
If you're GUI is running as a standard modal dialog you should get tabbing and Alt key navigation between controls for free. ie: controls with the WS_TABSTOP style set you should be able to tab to, controls with short cut key defined (eg: a button with a caption of "&Do Something" should be accessible with Alt+D - an...
1,399,063
1,399,076
C++ #define preprocessor
I need to know that does the #define directive in C++ declares global label? By global I mean visible in every file? I'm using Visual Studio 2008, (guess if that matters)
No, only in the current translation unit. I.e. every file which has #define, or includes a file that has the #define will see the definition. Edit, to respond to your comment: to get a define in every file, either put it in a header which gets included everywhere, or use some compiler option to get defines added. e.g....
1,399,215
1,399,292
Difference between _declspec and __declspec?
I sometimes see keywords starting with two underscores and other times just one. Is there any difference?
I believe that _declspec is older name of the same Microsoft specific keyword __declspec. From a C++ Standard point of view, two underscores are more correct than a single underscore for an extension like this. That's according to 17.4.3.1.2/1: Certain sets of names and function signatures are always reserved to the i...
1,399,275
1,399,356
Simplifying FOR loops
I have a function that essentially reads values in from a vector of doubles, appends these to a string (while ensuring a space between each and setting their precisions) and returns the end result, minus the final whitespace: std::string MultiplePrintProperties::GetHpitchString() { std::string str; vect...
Since you're actually transforming doubles into strings, and appending these strings to a stringstream, you can use std::transform for that: // your functor, transforming a double into a string struct transform_one_double { std::string operator()( const double& d ) const { boost::format fmt( "%.3f " ); re...
1,399,492
1,402,431
Image warp with VTK?
I'd like to warp a vtkImageData with a vector field, similar to what itk's WarpImageFilter does. the vtkGridTransform object seems promising, but there doesn't seem to be a vtkTransformImageFilter... Is what I want to do at all possible with VTK? Thanks a lot!
Ok, here's the answer: The filter for applying a transform to an image is vtkImageReslice, and the relevant example is Hybrid/Testing/Tcl/TestGridWarp3D.tcl. The basics of deformable transformations in VTK are described in the following paper: "Generalized 3D nonlinear transformations for medical imaging: an o...
1,399,666
1,399,697
Attaching char buffer to vector<char> in STL
What is the correct (and efficient) way of attaching the contents of C buffer (char *) to the end of std::vector<char>?
When you have a vector<char> available, you're probably best calling the vector<char>::insert method: std::vector<char> vec; const char* values="values"; const char* end = values + strlen( values ); vec.insert( vec.end(), values, end ); Delegating it to the vector is to be preferred to using a back_inserter because ...
1,399,669
1,399,943
How to link graphviz with VIsual C++
Someone please tell me How to link graphviz( or call its code) in C++ (VIsual Studio)
Graphviz has a documentation Using Graphviz as a library. Is that what are you searching for? Just in case, here described how to use libraries in Visual C++.
1,399,692
1,399,728
w8004 compiler warning BDS6 c/c++
It is a best practise to initialise a variable at the time of declaration. int TMyClass::GetValue() { int vStatus = OK; // A function returns a value vStatus = DoSomeThingAndReturnErrorCode(); if(!vStatus) //Do something else return(vStatus); } In the debug mode, a statement like thi...
You initialise vStatus to OK, then you immediately assign a new value. Instead of doing that you should initalise vStatus with a value that you're going to use. Try doing the following instead: int TMyClass::GetValue() { // A function returns a value int vStatus = DoSomeThingAndReturnErrorCode(); if(!vStatu...
1,399,891
1,399,985
c++ vector<char> and sockets
Is there a way to call send / recv passing in a vector ? What would be a good practice to buffer socket data in c++ ? For ex: read until \r\n or until an upper_bound ( 4096 bytes )
std::vector<char> b(100); send(z,&b[0],b.size(),0); Edit: I second Ben Hymers' and me22's comments. Also, see this answer for a generic implementation that doesn't try to access the first element in an empty vectors.
1,400,660
1,400,673
What is a common C/C++ macro to determine the size of a structure member?
In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent: typedef struct myStruct { int x[10]; int y; } myStruct_t; const size_t sizeof_MyStruct_x = sizeof(myStruct_t....
In C++ (which is what the tags say), your "dummy variable" code can be replaced with: sizeof myStruct_t().x; No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression. This works in C, and in C++ is better because it also works for classes...
1,400,787
1,702,677
getting an error of "Service not found" in a async_resolve handler
I have code that looks like the following: //unrelated code snipped resolver.reset(new tcp::resolver(iosvc)); tcp::resolver::query query(host, port); resolver->async_resolve(query, boost::bind(&TCPTransport::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); ...
In Boost it looks like that error can only happen as a result of a call to getaddrinfo(). In MSDN (for what it's worth), it sounds like the service name (or port) isn't supported for the types of socket that the caller (ASIO?) supports. In other words, it seems like you're attempting a TCP connection on either a non-T...
1,400,856
1,400,884
I can't understand this line - dereferencing an address of private member variable or what?
I asked a question while ago about accessing the underlying container of STL adapters. I got a very helpful answer: template <class T, class S, class C> S& Container(priority_queue<T, S, C>& q) { struct HackedQueue : private priority_queue<T, S, C> { static S& Container(priority_queue<T, S, C>& ...
Think of it like this: (q).*(&HackedQueue::c); First, you have HackedQueue::c, which is just the name of a member variable. Then you take &HackedQueue::c, which is a pointer to that member variable. Next you take q, which is just an object reference. Then you use the "bind pointer to member by reference" operator ....
1,400,954
1,400,970
How does this C++ code compile without an end return statement?
I came across the following code that compiles fine (using Visual Studio 2005): SomeObject SomeClass::getSomeThing() { for each (SomeObject something in someMemberCollection) { if ( something.data == 0 ) { return something; } } // No return statement here } Why does ...
This is to support backwards compatibility with C which did not strictly require a return from all functions. In those cases you were simply left with whatever the last value in the return position (stack or register). If this is compiling without warning though you likely don't have your error level set high enough...
1,401,342
1,406,385
Why is linker optimization so poor?
Recently, a coworker pointed out to me that compiling everything into a single file created much more efficient code than compiling separate object files - even with link time optimization turned on. In addition, the total compile time for the project went down significantly. Given that one of the primary reasons for ...
I'm not a compiler specialist, but I think the compiler has much more information available at disposal to optimize as it operates on a language tree, as opposed to the linker that has to content itself to operate on the object output, far less expressive than the code the compiler has seen. Hence less effort is spent ...
1,401,522
1,401,703
Scheduled Task Communication (using ITask interface)?
Is there anyway using the ITask interface to communicate with a scheduled task? I have tasks that users can cancel, pause, etc and a main console that displays information about the tasks. Right now I can only tell if they are running or not via the GetStatus method. What I would like to do is connect to the task and p...
The only strings you can pass to an ITask object are a directory path and command-line parameters. You cannot communicate with the task itself while it is running. On the other hand, if you use the Task Scheduler 2.0 interfaces instead, then ITaskDefinition has a Data property that you can assign arbitrary text to.
1,401,825
1,402,029
Callback from a C++ dll to a delphi application
Application is written in delphi 2010 and the underlying dll is a C++ dll. In ideal case, when your application is in C++; The dll makes a callback to an application when an event occurs. The callback is implemented through an interface. Application developers implements the abstract c++ class and pass the object to t...
I wouldn't really call that ideal. It is selfish and short-sighted to make a DLL that requires its consumers to use the same compiler as the DLL used. (Class layout is implementation-defined, and since both modules need to have the same notion of what a class is, they need to use the same compiler.) Now, that doesn't m...
1,402,260
1,402,943
Static variable accessed from different compilation units potentially problematic?
When I started as at my first job as software developer I was assigned to create a system for that allows writing and reading C++ values (or objects) from and to a PDF document. This required a system for mapping types to an id and vice versa. The codebase was huge and there were several 'layers' of code (basic framewo...
Is it important that the "types" be assigned the same IDs between different runs of your program? If not, everything should be fine. If so... How are different "types" grabbing their IDs? One way might be: class FooType { private: static UniqueId myId; ... }; This invokes the static initialization order fiasco ...
1,402,341
1,402,396
Removing a node From Doubly Threaded LnkLst
Im trying to remove a single node from a doubly threaded linked list. What I have works..Its just terribly inefficient. I was wondering if I can get some expert advice or some while termination condition tips. Here is the function in which I remove 1 node from a set of Rating Nodes, stored in headByRating and a set of...
Two choices: 1) Use a high level library that solves the problem. Boost MultiIndex containers allow shared nodes with multiple ordered/mapped organizations. 2) Instead of two (sorted by rating and name) singly linked lists, use two doubly linked lists. Then deletion of a given node is O(1). To find a node quickly by...
1,402,483
1,402,525
Why is it so slow iterating over a big std::list?
As title suggests, I had problems with a program of mine where I used a std::list as a stack and also to iterate over all elements of the list. The program was taking way too long when the lists became very big. Does anyone have a good explanation for this? Is it some stack/cache behavior? (Solved the problem by changi...
Lists have terrible (nonexistent) cache locality. Every node is a new memory allocation, and may be anywhere. So every time you follow a pointer from one node to the next, you jump to a new, unrelated, place in memory. And yes, that hurts performance quite a bit. A cache miss may be two orders of magnitudes slower than...