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,580,063
1,580,359
High performance comparison of signed int arrays (using Intel IPP library)
We're trying to compare two equally sized native arrays of signed int values using inequality operations, <, <=, > and >=, in a high performance way. As many values are compared, the true/false results would be sotred in a char array of the same size of the input, where 0x00 means false and 0xff means true. To accompli...
You could do the comparison with PCMPEQD followed by a PACKUSDW and PACKUSWB. This would be something along #include <emmintrin.h> void cmp(__m128d* a, __m128d* b, v16qi* result, unsigned count) { for (unsigned i=0; i < count/16; ++i) { __m128d result0 = _mm_cmpeq_pd(a[0], b[0]); // each line compares 4 i...
1,580,332
1,580,351
std::pow gives a wrong approximation for fractional exponents
Here is what I mean trying to do double x=1.1402 double pow=1/3; std::pow(x,pow) -1; result is 0 but I expect 0.4465 the equation is (1 + x) ^3= 1.1402, find x.
1/3 is done as integer arithmetic, so you're assigning 0 to pow. Try pow(x, 1.0/3.0);
1,580,471
1,658,902
How to mix C++ and external buttons on seperate window?
I want to make a C++ button on Start>Run i.e but when I do it will not do signalled event? Im sorry I have seen that you do not get the question. Ok basically when you create a button with CreateWindowEx(); I want to do that but put on a different window with SetPArent which I have already done now the button does not ...
You need to apply the ancient but still-supported technique known in Windows as subclassing; it is well explained here (15-years-old article, but still quite valid;-). As this article puts it, Subclassing is a technique that allows an application to intercept messages destined for another window. An application...
1,580,614
1,596,962
http client blocks on recv()
I need some help writing an http client. The trouble comes when I try to receive data from a webserver. The recv() call blocks the program. Any better direction would be extremely helpful, I'll post my code below: if ( argc != 2 ) { cerr << "Usage: " << argv[0]; cerr << " <URI>" << endl; return 1; } else...
You are using a blocking TCP/IP socket, but you are not looking at the HTTP reply's "Content-Length" header to know how many bytes to read. Your current reading logic is calling recv() in a loop until 1024 bytes max have been received. If the server sends less than 1024 bytes, you are going to be blocked indefinately...
1,580,737
1,580,743
Question about pointers and objects?
Just wondering, if I statically create an object that has a pointer as a data member and then the object goes out of scope, what happens to the pointer? Chuma
Nothing happens to the pointer at all, it just ceases to exist. If it was pointing to something that needed to be freed, you just got a memory leak. Either add code to the destructor that does the proper cleanup of the pointer, or use "smart pointers" that clean up after themselves automatically. Edit: If you actually ...
1,580,757
1,580,778
What is the official name of C++'s arrow (->) operator?
I always call it the "arrow operator", but I'm sure it has an official name. I quickly skimmed the C++ standard and didn't see it mentioned by name.
The C++ standard just calls it "arrow" (§5.2.5).
1,580,935
1,580,959
Declaring char[][512]?
I have an C++ SDK that requires a char[][512] as a parameter. I know that this is supposed to be a list of file names and the number of files could vary. For the life of me I cannot figure out how to declare this. I have an array of CStrings and I am trying to copy them over using strcpy_s and then pass them into the S...
This declaration has a special meaning when used to declare parameter of a function. Within the parameter list it is equivalent to char[100][512], char[123][512], char[3][512] (you get the idea - the first size can be just anything, it is simply ignored) and also to char (*)[512]. Effectively, it will accept as an argu...
1,580,960
1,580,981
Are these placement new macros correct?
I made a couple macros to make using placement new a bit easier. I was just wondering if there were any obvious cases where these would not work. Thanks. #define CONSTRUCT_INPLACE(TYPE,STORAGE,INIT) ::new((TYPE*)STORAGE) TYPE INIT #define DESTRUCT_INPLACE(TYPE,STORAGE) ((TYPE*)STORAGE)->~TYPE()
I'm not an expert in placement new but there are a couple of issues with how you are defining the macro. Issue 1 The most obvious problem is the use of the cast (TYPE*)STORAGE for the storage location. This is incorrect. Placement new is just another C++ function and it participates in operations like overload reso...
1,581,105
1,610,124
Running C++ binaries without the runtime redistributable (Server2k3, XPSP3)
Having written a CGI application in Visual Studio 2008 and debigged it locally, I uploaded it to a Windows Server 2003 OS where it promptly failed to run. I am guessing I need to install the wretched Runtime distributable, but after reading this: http://kobyk.wordpress.com/2007/07/20/dynamically-linking-with-msvcrtdll-...
A fuller list of options: Rewrite the app so that theres no C/C++ usage at all. Switch to Visual Studio 6 or a mingw based toolset like Code::Blocks - these use the already distributed msvcrt.dll as their runtime. Build using the /MT switch. This builds the necessary runtime functions into your exe. Which will bloat i...
1,581,348
1,581,359
Allocate room for null terminating character when copying strings in C?
const char* src = "hello"; Calling strlen(src); returns size 5... Now say I do this: char* dest = new char[strlen(src)]; strcpy(dest, src); That doesn't seem like it should work, but when I output everything it looks right. It seems like I'm not allocating space for the null terminator on the end... is this right? ...
You are correct that you are not allocating space for the terminator, however the failure to do this will not necessarily cause your program to fail. You may be overwriting following information on the heap, or your heap manager will be rounding up allocation size to a multiple of 16 bytes or something, so you won't ne...
1,581,390
1,581,393
Expected constructor, destructor, or type conversion before '::' token
I get the below error when compiling my file. //Error PluginDiskstats.cpp:107: error: expected constructor, destructor, or type conversion before '::' token scons: *** [PluginDiskstats.o] Error 1 // destructor ~PluginDiskstats::PluginDiskstats() // line 107 { if (stream != NULL) { fclose(stream); ...
Change line 107 to: PluginDiskstats::~PluginDiskstats()
1,581,443
1,582,397
Profiler for a C++ module in a C# app
I rewrote a number-crunching two pages of code from C# to unmanaged C++ in my project, which with full optimizations gave a 3x speedup. I want to keep optimizing that code, but now my profiler of choice, dotTrace, can't do it, because it only looks at managed code. How do I profile the P/Invoked C++ module when it's ru...
How about making a standalone test harness for the C++ code and profiling it alone with any number of tools like VTune, callgrind, Quantify, oprofile...?
1,581,508
1,581,512
Virtual non-method members
Is something similar to this possible? This way it produces an error. class A { public: virtual std::string key; }; class B : public A { public: std::string key; }; int main() { A a; a.key = "Foo"; return 1; }
No, because this doesn't really make sense. Remember that a subclass contains all members of its parent class; therefore, B still has A's std::string key. Moreover, since B's std::string key is the same type, it's absolutely identical to A's - so what was the point of overriding it? Also, note that during construction,...
1,581,539
1,581,567
How to identify a new line in C++?
I have to take integer input to an integer array. I have to identify the newline also in input. To be more clear, I have an example. The input I am giving is:- 2 3 4 45 6 78 45 34 34 I want to process the input according to the newline in the input. The programming language is C++ and the compiler is g++. I don't wa...
You can use std::getline from <string> to read whole lines and use a std::stringstream, from <sstream> to parse the lines.
1,581,763
1,581,858
Difference between A* pA = new A; and A* pA = new A();
in C++, what is the exact difference between both following dynamic object creations : A* pA = new A; A* pA = new A(); I did some tests, but it seems that in both cases, the default constructor is called and only it. I'm looking for any difference about performance... Thanks
If A is a POD-type, then new A will allocate a new A object but leave it with an indeterminate value, otherwise new A will default initialize the new object. In all cases new A() will value initialize the new A object. This is obviously different behaviour for POD types but also affects non-POD, non-union class types w...
1,581,778
1,646,213
How do you rotate a sprite around its center by calculating a new x and y position?
I'm using Dark GDK and C++ to create a simple 2d game. I'm rotating an object but it rotates from the top left corner of the sprite. I have the following variables available: PlayerX PlayerY PlayerWidth PlayerHeight RotateAngle (360 > x > 0) Is there an algorithm that will modify the pivot point of the sprite, pref...
The answers so far are correct in telling you how it should be done but I fear that the Dark GDK API seems to be too primitive to be able to do it that simple way. Unfortunately dbRotateSprite rotates the sprite about the top left regardless of the sprite's transform which is why you're having no luck with the other su...
1,581,809
1,581,933
create a object : A.new or new A?
Just out of curiosity: Why C++ choose a = new A instead of a = A.new as the way to instantiate an object? Doesn't latter seems more like more object-oriented?
Just out of curiosity: Why C++ choose a = new A instead of a = A.new as the way to instance-lize an object? Doesn't latter seems more like more object-oriented? Does it? That depends on how you define "object-oriented". If you define it, the way Java did, as "everything must have syntax of the form "X.Y", where X i...
1,581,818
1,581,838
How to call a function from binary data
I have some binary data which contains a bunch of functions and want to call one of it. I know the signature of these functions along with the offset relative to the start of the file. Calling convention is the default one: __cdecl. The file was already loaded into a memory page with executing permissions. For example ...
// define a function pointer typedef __cdecl void (*your_function) (A *arg1, B arg2, C arg3); your_function ftr; char * memory = 0x123456; // base segment address fptr = (your_function)(memory + 0x42); //calculate memory address (*ftpr)(a,b,b); // call function
1,581,839
1,581,853
what's the mechanism of sizeof() in C/C++?
It seems sizeof is not a real function? for example, if you write like this: int i=0; printf("%d\n", sizeof(++i)); printf("%d\n", i); You may get output like: 4 0 And when you dig into the assemble code, you'll find sth like this: movl $4, %esi leaq LC0(%rip), %rdi xorl %eax, %eax call _printf So, the co...
You know, there's a reason why there are standard documents (3.8MB PDF); C99, section 6.5.3.4, §2: The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If t...
1,581,925
1,582,111
Operations and functions that increase Virtual Bytes
Having some out-of-memory problems with a 32-bit process in Windows I begun using Performance Monitor to log certain counters for that process. Though it is normal that Virtual Bytes is higher than both Private Bytes and Working Set, I found that in my case there was a substantial difference, Virtual Bytes was much hig...
Things that (may) increase virtual bytes without increasing private bytes I can think of right now: Binaries are often shared (i.e. not private), but occupy significant address space. This can be even larger than the size of the binary Using VirtualAlloc to reserve sequential address space without committing / accessi...
1,582,095
1,585,448
Test driven development for C++ XPCOM component?
I want to create a Firefox extension using c++ XPCOM component which in turn uses javascript XPCOM component. Is there any framework that allows test driven development of C++ XPCOM component/firefox extension ?
You could copy what Mozilla uses to test native code. You just have to make sure you link with libxul (which may require that you build Firefox). An example file that uses TestHarness.h can be found here.
1,582,372
1,582,509
How can I convert from DWORD RGBA to ints?
I have to convert a DWORD (unsigned long) RGBA to four int vars (R, G, B, and A) So far, I have this function to convert the 4 ints to a DWORD: unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA) { return ((iA << 24) | (iR << 16) | (iG << 8) | iB); } How can I convert it back? Something like struct RGBA { ...
If I were you, I'd stick with multiplicative-additive operations in the packing/unpacking functions. Something like this unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA) { return ((iA * 256 + iR) * 256 + iG) * 256 + iB; } with a symmetrical unpacking function RGBA DWORD2RGBA(unsigned long dwColor) { ...
1,582,404
1,635,107
QtCreator delete file is not working
I'm writing a "custom makefile" project using QtCreator and I want to delete a file of my project, so, I select the file in the tree view, press the right click and the "delete" option is disabled and I did not find any way of enable it. My environment: QtCreator 1.2.1 on SnowLeopard: Thanks in advance, Ernesto
By the way, I downloaded and installed Qt creator 1.3 beta for Mac OS X and deleting files is working properly.
1,582,704
1,582,716
Need help with three visual studio errors - C++ errors occuring when trying to build solution
I get the following errors when I try to build this project: error C2182: 'read_data':illegal use of type 'void' error C2078: too many initializers errors c2440: 'initializing': cannot convert from 'std::ofstream' to int All of the above seem to be pointing to my function call on line 72, which is this line: void rea...
Yes, the problem is the line void read_data(finput, foutput); inside the main function. Don't specify the return type when calling the function. Only when declaring it. In other words, the line should just read read_data(finput, foutput);
1,582,737
1,582,763
What is the simplest way to execute arbitrary process with stdin, stdout forwarded to a socket?
I'm interested in two situations: How to do it from C++? How to do it from system's shell? Answers for Linux, Windows and OSX are welcome.
Linux/OSX (actually POSIX), programming (any language that have POSIX calls), general scheme: setup a socket... fork() close(0), close(1) (not necessary, dup2 will close it too... but added for clarity) dup2(socket, 0), dup2(socket, 1) exec() Shell: use nc. Example in my other answer: https://stackoverflow.com/questi...
1,582,790
1,582,931
Network programming: SOAP vs DIY marshalling with XML library?
I know that there are a lot of discussions already on SO about SOAP, bloat, XML, and alternative mechanisms like REST. Here's the situation. A new team member is really talking up SOAP based upon the difficulty of implementing protocols by hand. He recommends gSOAP (project is all in C++.) He is stating things like WSD...
I think that you will find that PHP developers are more likely to prefer RESTful interfaces. Here is a 2003 article about it. http://onlamp.com/pub/a/php/2003/10/30/amazon_rest.html RESTful interfaces are a growing phenomenon and if you need to attract developers to your platform it will be easier if you catch the wave...
1,582,877
1,582,918
How to find free memory within a specific address range
I want to write a small amount of memory inside of a specific address range of my process. Example amount of memory to allocate: 5 bytes lower bound for address: 0x 00 40 00 00 upper bound for address: 0x 00 A0 00 00 The range in which I want to write is already allocated by the process. Therefore, I can't simply all...
I don't think there's a nice, general way to do what you're wanting. Since it looks like you're talking about Windows and about where the default spot to load a PE is, I'll make some assumptions here that might help you. If you're willing to parse the PE-header, you can generally find slack-space in there. Check out ...
1,583,011
1,583,037
Compiler warning with nested vectors of depth 3 or more
I am trying to use a class member that uses nested vectors of depth 3: vector< vector< vector > > classVariable_; However, I then get compiler warnings throughout my code when I try do something as simple as classVariable_.clear(): /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_vector.h: In member function `std...
If you actually mean vector< vector< vector< int> > > classVariable_, then classVariable_.clear() shouldn't produce any warning. Might be this bug. Disable the warning manually, or avoid nested vectors of depth 3, which might not be a good idea anyway.
1,583,184
1,583,204
How to print result of C++ evaluation with GDB?
I've been looking around but was unable to figure out how one could print out in GDB the result of an evaluation. For example, in the code below: if (strcmp(current_node->word,min_node->word) > 0) min_node = current_node; (above I was trying out a possible method for checking alphabetical order for strings, and ...
There is no expression-level single stepping in gdb, if that's what you are asking for. Your options are (from most commonly to most infrequently used): evaluate the expression in gdb, doing print strcmp(current_node->word,min_node->word). Surprisingly, this works: gdb can evaluate function calls, by injecting code in...
1,583,234
1,583,259
C++ system() function — How to collect the output of the issued command?
I'm running some commands with the C++ system() function: int system ( const char * command ); How can I collect the standard output from the issued commands? To be specific, I want to collect the output of the issued command (for example, the directory listing output from issuing the dir command).
Are you looking for returned value (as in "exit status") of the executed command, or for its output (as in "what did it print")? If the latter, use popen() and pclose() instead. If the former, look at the return value from system() (and use the documentation for waitpid() to interpret it).
1,583,413
1,583,422
Find a prime number?
To find whether N is a prime number we only need to look for all numbers less or equal to sqrt(N). Why is that? I am writing a C code so trying to understand a reason behind it.
N is prime if it is a positive integer which is divisible by exactly two positive integers, 1 and N. Since a number's divisors cannot be larger than that number, this gives rise to a simple primality test: If an integer N, greater than 1, is not divisible by any integer in the range [2, N-1], then N is prime. Otherwis...
1,583,436
1,583,506
What is the most efficient way to keep a steady frame rate with DirectX and C++?
I'm learning DirectX from a book about game programming, and it uses the following method for a game loop: long int start = GetTickCount(); while(true) GameRun(); void GameRun() { if(GetTickCount() - start >= 30) //do stuff } This makes start equal whatever the time is (I'm guessing get tick count g...
For your game loop, read this article. It sum-up your options and makes your choice clear. Now for GetTickCount(), it's the simplest way to get time in Windows (I don't know the one for unix OSes). QueryPerformanceFrequency and QueryPerformanceCounter gives far more precision but might be hard to understand how to use ...
1,583,444
1,583,451
Does d3d9.h include windows.h? (C++)
When I use #include <d3d9.h> in my programs, I no longer need to include windows.h to use windows functions like WinMain, and CreateWindow. Is this because d3d9.h &c. include windows.h? Mainly, I'm wondering if it is possible to substitute windows.h with d3d9.h, etc, and still be able to se any functions I could use w...
Yes, if you open d3d9.h you will see # include <windows.h>.
1,583,509
1,583,525
Why won't my sorting method work?
I have an issue with my C++ code for college. I can't seem to understand why my sRecSort() method isn't working. Any help? This is really confusing me! #include <iostream> #include <algorithm> #include <string> #include <fstream> #include <sstream> using namespace std; void sRecSort(string n[], int s[], string e[], i...
Okay, the problem is in the inner loop condition. Can't tell you where exactly -- that's a homework. for (int i = 0; i < len; i++){ for (int j = 1; j < len; j++){ // <--- this line is wrong The first element of your "sorted" array will correctly be the lowest. But the others... P.S. Irrelevant to the problem, ...
1,583,547
1,583,568
How does get object from point work?
I'm new to programming. I want to make a card game with C++ / Allegro. The graphics api is irrelevant though. I want it to have many buttons you can click. I'm wondering the proper way this is done. For instance, how does windows know which control you click on from your cursor. I would use an array of rectangles and c...
Basically, you want to make a mouse-driven user interface. This is very difficult to do from scratch, that's why Allegro has a built-in GUI system. If you don't like it, you'd better use a GUI library than doing it yourself. I'd recommand MasKing, it's an add-on for Allegro, to write graphical interfaces in C++.
1,583,652
1,583,656
How to read cin with whitespace up until a newline character?
I wish to read from cin in C++ from the current position up until a newline character into a string. The characters to be read may include spaces. My first pass fails because it stops on the first space: string result; cin >> result; If cin is given: (cd /my/dir; doSometing)\n The variable result only gets: (cd I...
std::string str; std::getline( std::cin, str);
1,583,791
1,584,079
constexpr and endianness
A common question that comes up from time to time in the world of C++ programming is compile-time determination of endianness. Usually this is done with barely portable #ifdefs. But does the C++11 constexpr keyword along with template specialization offer us a better solution to this? Would it be legal C++11 to do so...
Assuming N2116 is the wording that gets incorporated, then your example is ill-formed (notice that there is no concept of "legal/illegal" in C++). The proposed text for [decl.constexpr]/3 says its function-body shall be a compound-statement of the form { return expression; } where expression is a potenti...
1,583,834
1,583,992
Is this the right approach for a thread-safe Queue class?
I'm wondering if this is the right approach to writing a thread-safe queue in C++? template <class T> class Queue { public: Queue() {} void Push(T& a) { m_mutex.lock(); m_q.push_back(a); m_mutex.unlock(); } T& Pop() { m_mutex.lock(); T& temp = m_q.pop(); m_mutex.unlock(); return temp; } ...
Herb Sutter wrote an excellent article last year in Dr. Dobbs Journal, covering all of the major concerns for a thread-safe, lock-free, single-producer, single-consumer queue implementation. (Which made corrections over an implementation published the previous month.) His followup article in the next issue tackled a mo...
1,583,966
1,583,973
C++ stack overflow - visual studio 2008
I declared and initialized an array having [100][1000][1000] char elements(100MB), it didn't say about a stack overflow at the first time.But when I running it after a while it throws a Stack overflow exception! I increased the -Stack Reserve Size- to 200,000,000 in project options->linker->system but it didn't worked!...
Stop using the stack! Use heap memory!
1,583,989
1,583,996
Most optimal way to find the sum of 2 numbers represented as linked lists
I was trying to write a program for the problem I mentioned above, the numbers (i.e the lists) can be of unequal length, I was not able to figure out a way to do this other than the most commonly thought of approach i.e reverse list-1 reverse list-2 find the sum and store it in a new list represented by list-3 reve...
Ideally the first thing I would do is store the numbers in reverse digit order, so 43,712 is stored as: 2 -> 1 -> 7 -> 3 -> 4 It makes arithmetic operations much easier. Displaying a number can be done either iteratively or more simply with a recursive algorithm. Note: all this assumes singly-linked lists. Edit: But y...
1,584,090
1,584,098
Visual Studio Debugger can't view arrays after they have been passed to functions
I have a function like this: MyFunction(double matrix[4][4]) {/*do stuff*/} I am calling this from an outer function (the otuer function is a member function of a class, in case that matters): OuterFunction() { double[4][4] x; initialize(x); //this function puts the data I want in the matrix MyFunction(x); } I am try...
It is can be solved by using a vector of vectors, or having your matrix variable in the watch windows like "matrix,4". The ",4" is a format that tells the debugger show 4 elements.
1,584,100
1,584,114
Converting multidimensional arrays to pointers in c++
I have a program that looks like the following: double[4][4] startMatrix; double[4][4] inverseMatrix; initialize(startMatrix) //this puts the information I want in startMatrix I now want to calculate the inverse of startMatrix and put it into inverseMatrix. I have a library function for this purpose whose prototype is...
No, there's no right way to do specifically that. A double[4][4] array is not convertible to a double ** pointer. These are two alternative, incompatible ways to implement a 2D array. Something needs to be changed: either the function's interface, or the structure of the array passed as an argument. The simplest way to...
1,584,202
42,268,952
GDI+ Bitmap Save problem
Bitmap bff(L"1.jpg"); bff.Save(L"2.jpg", &Gdiplus::ImageFormatJPEG, NULL); This creates a new file 2.jpg with zero-bytes length. Isn't it supposed to write an image file that is identical to 1.jpg? Why I'm having zero-bytes length files? I'm doing this test because writing other Bitmaps to files, result in the same ...
Here's a fast way to save it, since GetEncoderClsid is a custom function: //Save to PNG CLSID pngClsid; CLSIDFromString(L"{557CF406-1A04-11D3-9A73-0000F81EF32E}", &pngClsid); bmp.Save(L"file.png", &pngClsid, NULL); and here's IDs for other formats: bmp: {557cf400-1a04-11d3-9a73-0000f81ef32e} jpg: {557cf401-1a04-11d3-9...
1,584,206
1,606,745
Problems communicating with external editor in Qt4
I am writing a command-line Qt4 script (using QCoreApplication) on Mac OS X. I am using this code adapted from C++ Programming with Qt 4, 2nd ed. p. 313: QTemporaryFile outFile; if (!outFile.open()) return; QString fileName = outFile.fileName(); QTextStream out(&outFile); out << initial_text; outFile.close(); QPr...
It seems your editor "/Users/jason/bin/mate" doesn't support a filename being passed as an argument. From your terminal, try something like: echo "Test text" > test.txt /Users/jason/bin/mate test.txt To see if it opens the editor with the right text.
1,584,296
1,584,306
unsigned char array to unsigned int back to unsigned char array via memcpy is reversed
This isn't cross-platform code... everything is being performed on the same platform (i.e. endianess is the same.. little endian). I have this code: unsigned char array[4] = {'t', 'e', 's', 't'}; unsigned int out = ((array[0]<<24)|(array[1]<<16)|(array[2]<<8)|(array[3])); std::cout << out << std::endl; ...
This is because your CPU is little-endian. In memory, the array is stored as: +----+----+----+----+ array | 74 | 65 | 73 | 74 | +----+----+----+----+ This is represented with increasing byte addresses to the right. However, the integer is stored in memory with the least significant bytes at the left: +...
1,584,380
1,584,679
In C++, how system implement the buffered stream?
Can someone write some sample code to explain this concept? I know what a buffered stream is used for, but I also would like to know how to implement that. Thanks in advance!
You can look into your platform's implementation, the C++ standard or "Standard C++ IOstreams and Locales" by Angelika Langer and Klaus Kreft. Be prepared for quite a learning curve. Streams are old and a complicated matter. (Francis Glassborow: "I have very few doubts that I/O libraries are amongst the most difficult...
1,584,421
1,584,478
Can't use DLL (written in C++) in Delphi: The procedure entry point could not be located
I've compiled a DLL in Visual Studio (the source code is in C++, which I barely understand). Here's a piece of Scraper.h: struct SWin { char title[512]; HWND hwnd; }; SCRAPER_API bool ScraperGetWinList(SWin winList[100]); Now I'm trying to use the above function in my Delphi application: type tWin = record ...
From my Linux experience, I'd say that you've encountered so-called "name-mangling" issue. The entry point of your procedure is not called "ScraperGetWinList", but something like "_ZN18ScraperGetWinListEpN4SWin". The thing is that, Unlike in C, in C++ language the name of entry point is not the same as the function na...
1,584,502
1,584,553
LoadLibraryW doesn't work while LoadLibraryA does the job
I have written some sample program and DLL to learn the concept of DLL injection. My injection code to inject the DLL to the sample program is as follows (error handling omitted): std::wstring dll(L"D:\\Path\\to\\my\\DLL.dll"); LPTHREAD_START_ROUTINE pLoadLibraryW = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32...
HMODULE WINAPI LoadLibrary( __in LPCTSTR lpFileName ); It takes a TCHAR -- so the argument for LoadLibraryW has to be a wide string; the code above passes the multi-byte form of the argument, which is the form that LoadLibraryA wants.
1,584,702
1,584,712
Some questions on C++ struct and array
I am relatively new to C++ and am having problems understanding struct. I have a struct declared as follow struct MyNode { int level; int index; MyNode children[4]; } However the code fails to compile and reports error C2148: total size of array must not exceed 0x7fffffff bytes. But the following code comp...
This fails to compile, because the compiler needs to know the size of each type. So, what's sizeof(MyNode) ? It's sizeof(int) * 2 + sizeof(MyNode) : The recursion makes the size impossible to figure out. You need a pointer, as in your second example. Why does this works ? Because sizeof(MyNode*) is known : it's the siz...
1,584,754
1,584,775
How to include lua scripting language into C++ XCode?
I have successfully compiled lua in my mac. It works. It runs. Now, I want to mix it with C++ in XCode. So I looked up in the Linked Library, the usual place to add more libraries in XCode. But of course, lua isn't there. Now, how do I tell XCode the existence of lua so that the program can include lua.h correctly?
Up to you : use the "Header Search Path" and "Library Search Paths" in the properties to add the location of Lua headers and liblua.a OR just copy the Lua headers and liblua.a in your project directory, then add them to your project
1,584,835
1,584,856
In what order do C++ objects passed as arguments to constructors of other objects go out of scope?
When I compile the following code with g++, the object of class A seems not to be destructed when the object of class C is constructed, and the B.ref_a reference is not broken when accessed by the constructor of object of class C: #include <iostream> struct A { A(int aa) { a = aa; } ~A() {...
Here, the temporary objects go out of scope when the instruction has finished its execution. That is, just after the constructor of C has returned. And yes, this is guaranteed by the C++ standard.
1,584,956
1,586,277
How to handle execvp(...) errors after fork()?
I do the regular thing: fork() execvp(cmd, ) in child If execvp fails because no cmd is found, how can I notice this error in parent process?
The well-known self-pipe trick can be adapted for this purpose. #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/wait.h> #include <sysexits.h> #include <unistd.h> int main(int argc, char **argv) { int pipefds[2]; int count, err; pid_t child; if (pipe(pipefds))...
1,585,056
1,610,085
How to make XCode put required resources in "build" folder?
I am trying out lua script with C++ in Mac OS X. I was finding a way to make the program returning the current working directory. That's no problem with getcwd, but then I came one thing: My foo.lua stays at its initial path only. When I compile program, it is not being copied over to the build/Debug directory. Sure, I...
Rather than hard code the path to your Lua script you may want to use the NSBundle API's to find it: NSBundle * mainNSBundle = [NSBundle mainBundle]; NSString * luaFilePath = [mainNSBundle pathForResource:@"foo" ofType:@"lua" inD...
1,585,137
1,585,164
What happens in assembly language when you call a method/function?
If I have a program in C++/C that (language doesn't matter much, just needed to illustrate a concept): #include <iostream> void foo() { printf("in foo"); } int main() { foo(); return 0; } What happens in the assembly? I'm not actually looking for assembly code as I haven't gotten that far in it yet, ...
In general, this is what happens: Arguments to the function are stored on the stack. In platform specific order. Location for return value is "allocated" on the stack The return address for the function is also stored in the stack or in a special purpose CPU register. The function (or actually, the address of the func...
1,585,188
1,588,486
SDL_Mixer sound problems
Basic Info: Programming Language - C++ Platform - Windows Audio Formats - wav and mid I recently finished a game and was fooling around with figuring out the best way to upload it to a file hosting site. I eventually decided on using 7zip's self-extracting feature. However, I think the mistake I made was that instead o...
This could be a number of things. It could be an issue with the SDL_Mixer library you have, so you could try getting it again to rule that out. Your volume may have somehow got set to zero somewhere, so I would check the volume as a test. And the final thought would be that the source sound file you are playing is i...
1,585,302
1,585,332
Which STL reference book would recommend?
I am considering to put one of the following as a reference on my desk (as I am sick and tired to google every time I have a STL question): The C++ Standard Library: A Tutorial and Reference STL Tutorial and Reference Guide: C++ Programming with the Standard Template Library Generic Programming and the STL: Using and...
All of Scott Meyers' books are excellent, including "Effective STL". It's not a handbook or a tutorial, but worth having.
1,585,515
1,585,522
What does typedef do in C++
typedef set<int, less<int> > SetInt; Please explain what this code does.
This means that whenever you create a SetInt, you are actually creating an object of set<int, less<int> >. For example, it makes the following two pieces of code equivalent: SetInt somevar; and set<int, less<int> > somevar;
1,585,674
1,590,924
Subclass of QGraphicsLayoutItem for stretchers?
The specializations of QGraphicsLayout (e.g. QGraphicsLinearLayout) include an insertStretch method. What kind of object do QGraphicsLinearLayout::insertStretch method insert in the list of items managed by the layout? Better asked: what type of object is returned by QGraphicsLayout::itemAt method when called for a str...
I've never investigated this, so I don't know, but if you are truly curious, you could ask for an object at that position. Assuming it doesn't return NULL, you could then work your way through the meta information and find out quite a bit of information about it. I wouldn't be too surprised, however, if it were a stoc...
1,585,708
1,585,711
Copy Constructor and default constructor
Do we have to explicitly define a default constructor when we define a copy constructor for a class?? Please give reasons. eg: class A { int i; public: A(A& a) { i = a.i; //Ok this is corrected.... } A() { } //Is this required if we write the above ...
Yes. Once you explicitly declare absolutely any constructor for a class, the compiler stops providing the implicit default constructor. If you still need the default constructor, you have to explicitly declare and define it yourself. P.S. It is possible to write a copy constructor (or conversion constructor, or any oth...
1,586,286
1,586,298
C++ fork() and execv() problems
I am kind of newbie on C++, and working on a simple program on Linux which is supposed to invoke another program in the same directory and get the output of the invoked program without showing output of the invoked program on console. This is the code snippet that I am working on: pid_t pid; cout<<"General sent...
You aren't distinguisng between the child and the parent process after the call to fork(). So both the child and the parent run execv() and thus their respective process images are replaced. You want something more like: pid_t pid; printf("before fork\n"); if((pid = fork()) < 0) { printf("an error occurred while for...
1,586,368
1,586,382
Assign a C++ out reference to something that was destroyed?
So I'm looking through some code, and I see this: class whatever { public: void SomeFunc(SomeClass& outVal) { outVal = m_q.front(); m_q.pop(); } private: std::queue<SomeClass> m_q; }; This doesn't seem like outVal would be a valid reference any more... However, it appears to work. ...
Remember that references are not like pointers: they cannot be rebound after their creation. That means that if I do int a; int b; int &c = a; Then throughout that scope, an assignment to c will actually mean an assignment to a. So, int a = 2; { int b = 3; int &c = a; c = b; b = -5; } printf("%d",a); // pr...
1,586,393
1,586,462
Custom C++ Preprocessor / Typeful Macros
Having seen the advantages of metaprogramming in Ruby and Python, but being bound to lower-level languages like C++ and C for actual work, I'm thinking of manners by which to combine the two. One instance comes in the simple problem for sorting lists of arbitrary structures/classes. For instance: struct s{ int a; i...
For the above, you can use Boost.Lambda to write your comparison function inline, just like a Python lambda: using namespace boost::lambda; std::sort(vec.begin(), vec.end(), (_1 ->* &s::a) < (_2 ->* &s::a)); This of course assumes that you are sorting by a. If the expressions you are looking for are far more complex,...
1,586,584
1,586,637
Why won't this code output to a file?
I've debugged my program and the arrays seem to be allocated well. However for some strange and stupid reason, the code doesn't output the arrays into the file. Please help me spot my bug or such! #include <iostream> #include <algorithm> #include <string> #include <fstream> using namespace std; void sRecSort(string *...
The code seems to be correct so far, I think your test data is wrong. If I test with this input file: a 10 c d 2 f g 9 i j 4 l m 8 o p 6 r s 7 u v 8 x y 6 a b 10 d e 5 g h 12 j The output file is like this, which is the expected behaviour: d 2 f j 4 l e 5 g y 6 a p 6 r s 7 u m 8 o v 8 x g 9 i b 10 d a 10 c h 12 j So ...
1,586,590
1,586,638
Instantiating objects and object members
For some reason the following doesn't crash like my program does, but I'm pretty sure it's similar in design. For one, the output's not correct. It outputs something similar to: 0x537ff4 5471612 While the main program outputs (nil) for the pointer address. The key to the problem might be display_ in Drv. Here's the co...
This code: Drv() : Generic((LCDText *)display_) { display_ = new Display((Generic *)this); }; first runs the parent class's ctor, with a yet-uninitialized value of display_, then independently sets display_, but, too late to change the parent class. So the pointer held by the parent class will never be set correc...
1,586,749
1,587,158
What is the difference between _itoa and itoa?
Visual Studio is yelling at me about using itoa() saying to use _itoa() instead? It looks to me like they are the same function. What gives?
A C run time library implementation is not supposed to introduce names that aren't in the standard unless they follow a certain naming convention (like starting with an underscore). The earlier versions of Microsoft's compiler didn't follow this rule particularly closely, but over time, Microsoft has been moving more ...
1,586,773
1,586,817
Checking if a Socket has closed in C++
I have a small application that redirects the stdout/in of an another app (usually command prompt or bash for windows). The problem is that if the connection is interrupted the my process has no idea and it never closes because of this line: WaitForSingleObject(childProcess.hThread, INFINITE) I was thinking of having ...
Note: I'm assuming the connected socket is communicating over a network link, because I'm not sure how it would become disconnected if it were a local pipe, except by one process or the other dying. Use the select() function in the socket API to query the read status of the socket. select() will tell you the socket i...
1,586,787
1,586,815
What is paging effect in C++?
I came across this as I was trying to learn array and vectors in c++. What is the "paging effect" mentioned in the post? Also, just to check my own understanding, I think vector uses more time is because of the dynamic memory allocation. Am I right? additional question: but with vector<int> arr( 10000 ) isn't there al...
Vector uses dynamic allocation if you use push_back(), but you can force it to pre-allocate memory with reserve(). Checked builds (common in debug libraries) also check the bounds for vector operations which can slow them down in debug mode. Release builds should be no slower than raw C. Paging means moving memory out...
1,586,795
1,586,887
Why does write() to pipe exit program when pipe writes to stdout?
I have a server application that writes to a popen("myCommand", "w") file descriptor in a separate thread and if the command passed to popen() results in any output to stdout or stderr, the my application exits. However, this is only an issue when my server application was invoked via inetd, if I used ssh to launch th...
you need to close all existed fds of the process before open the pipe, then do i/o redirection. that's because if inetd, the process runs as a daemon.
1,586,812
1,618,247
Why can't gdb attach to server application summoned with inetd?
I have a server application that can be summoned for the client using inetd. However, if I try to attach to the server process that was launched with inetd, I get the following response: ptrace: Operation not permitted. gdb --annotate=3 /my/app/here <processId> Current directory is /usr/local/bin/ GNU gdb 6.8 Copyrig...
Apparently, things get funky with inetd where the userid is not root. You end up with a process with weird permissions. For example, you are unable to read /proc/self/exe even though the permissions are 777. I suspect this issue is more of the same. Even though I'm the userid of the process, I don't have permission...
1,586,834
1,586,837
Escape sequence for ? in c++
I was looking at the escape sequences for characters in strings in c++ and I noticed there is an escape sequence for a question mark. Can someone tell me why this is? It just seems a little odd and I can't figure out what ? does in a string. Thanks.
It's to keep a question mark from getting misinterpreted as part of a trigraph. For example, in "What??!" The "??! would be interpreted as the | character. So, you have to escape the question marks as follows: "What\?\?!" Example complements of http://msdn.microsoft.com/en-us/library/bt0y4awe%28VS.80%29.aspx
1,586,907
1,586,952
C++ Simple file reading
I have a file,named f1.txt, whose contents are 75 15 85 35 60 50 45 70 Here is my code to read each integer and print them. #include <iostream> #include <fstream> using namespace std; int main(int argc, char *argv[]) { fstream file("f1.txt", ios::in); int i; while(!file.eof()) { file >> i; cout << i << "...
Try: while(file >> i) cout << i << " ";
1,587,005
1,587,011
Unusual HTTP Response in Basic C++ Socket Programming
I've got a basic HTTP client set up in C++, which works ok so far. It's for a school assignment, so there's lots more to do, but I'm having a problem. I use the recv() function in a while loop, to repeatedly add pieces of the response to my response buffer, and then output that buffer each time. The problem is, at the ...
The buffer isn't null terminated, which is required for strings in C++. When you see the "extra GET", you are seeing memory that you shouldn't be because the stdlib tried to print your buffer, but never found a '\0' character. A quick fix is to force the buffer to be terminated: int n = 1; while (n > 0) { n = recv(...
1,587,034
1,587,050
std::map::iterator crashes program on increment
What could cause this? Here's the stack trace: #0 0x0645c0f5 in std::_Rb_tree_increment (__x=0x83ee5b0) at ../../../../libstdc++-v3/src/tree.cc:69 #1 0x0805409a in std::_Rb_tree_iterator<std::pair<std::string const, Widget*> >::operator++ ( this=0xbffff144) at /usr/lib/gcc/i586-redhat-linux/4.4.1/../../.....
There could be quite a few reasons for that. For one, it may be that GetType or SetupChars or Start do something that causes your map to change - which would invalidate the current iterator (note that using operator[] on the map, even just to read the value, is technically a mutating operation, and can cause a crash wi...
1,587,252
1,587,272
What is a popular, multi-platform, free and open source socket library
Is there any free open source library (in C/C++) for sockets that is widely used and supports wide range of operating systems (Windows, Unix/Linux, FreeBSD etc). Just like pthreads. Otherwise the only solution left would be to write socket wrapper for each operating system. Or would writing a wrapper against winsock an...
I believe both the Apache Portable Runtime and GTK+'s GLib libraries have socket APIs. Since your question is tagged c and c++ I suspect you really want C++-centric answers, but both of these are good as pure C libraries.
1,587,410
1,587,413
Delphi: Access violation after calling function from external DLL (C++)
There's a function, written in C++ and compiled as DLL, which I want to use in my Delphi application. Scraper.cpp: SCRAPER_API bool ScraperGetWinList(SWin winList[100]) { iCurrWin=0; memset(winList,0,100 * sizeof(SWin)); return EnumWindows(EnumProcTopLevelWindowList, (LPARAM) winList); } Scraper.h: #ifdef ...
You need to put __stdcall after bool. The complete declaration, after all macros expand, should look like this: extern "C" { __declspec(dllexport) bool __stdcall ScraperGetWinList(SWin winList[100]); } EDIT: Looks like you'll also need a .def file there. It's a file that lists every function exported in the DL...
1,587,521
1,587,589
Keep windows trying to read a file
I'm working in a sort of encapsulation of the windows filesystem. When the user request to open a file, windows calls to my driver to provide the data. In normal operation the driver return the file contents which is cached, However, in some cases the real file is not cached and I need to download it from the network. ...
The behavior you implement is correct for a driver. The responsibility for handling slow I/O lies at a higher level. For instance, Windows Explorer is very careful in NOT trying to retrieve even a single byte from any file, relying purely on metadata. However, do not return a failure code when you're busy. It's that fa...
1,587,716
1,591,537
How can I get the IP address of a network printer given the port name using the Win32 API?
How can I get the IP address of a network printer given the port name, using win32 API? I tried looking into the PRINTER_INFO_* structs, but it seems it is not present there.
I don't think there's a standard way to get the IP address. There are probably different incompatible implementations of network port monitors. For my network printer, the IP address is part of the port name (e.g., IP_192_168.1.104). If it's of that form, then you might be able to parse it out, but I don't think thi...
1,588,131
1,588,289
C++ Array size x86 and for x64
Simple question, I'm writting a program that needs to open huge image files (8kx8k) but I'm a little bit confused on how to initialize the huge arrays to hold the images in c++. I been trying something like this: long long SIZE = 8092*8092; ///8096*8096 double* array; array = (double*) malloc(sizeof(double) * SIZE)...
Are you compiling your application as a 32-bit application (the default in Visual Studio, if that's what you're using), or as a 64-bit application? You shouldn't have troubles if you build it as a 64-bit app. malloc allocates (reserves memory and returns a pointer), calloc initializes (writes all zeros to that memory)...
1,588,665
1,588,714
Forcing an error when a function doesn't explicitly return a value on the deafult return path?
Is there a way, in VC++ (VSTS 2008), to froce a compiler error for functions that do not explicitly return a value on the default return path (Or any other quick way to locate them)? On the same issue, is there any gaurentee as to what such functions actually return?
I don't know exactly the warning number, but you can use #pragma warning for enforcing a specific warning to be treated as error: Example: #pragma warning( error: 4001) will treat warning 4001 as error
1,588,788
1,590,534
Wrapping C++ class API for C consumption
I have a set of related C++ classes which must be wrapped and exported from a DLL in such a way that it can be easily consumed by C / FFI libraries. I'm looking for some "best practices" for doing this. For example, how to create and free objects, how to handle base classes, alternative solutions, etc... Some basic gui...
Foreach public method you need a C function. You also need an opaque pointer to represent your class in the C code. It is simpler to just use a void* though you could build a struct that contains a void* and other information (For example if you wanted to support arrays?). Fred.h -------------------------------- #ifde...
1,588,866
1,591,746
Gtkmm - "Gtk::DrawingArea" in "Gtk::ScrolledWindow"?
I am making a GUI program using "gtkmm". I would like to draw some graphics to the "Gtk::DrawingArea" widget but I want that widget to be "resizable", so when I draw let's say a line from "(0, 0)" to "(50, 50)" pixel - the drawing area should be resized to a square of size "(50, 50)"; and when I for example draw a l...
Add a GTK::Viewport in between your ScrolledWindow and DrawingArea.
1,588,949
1,588,967
How to check if the first char in the line is # (beginning of a comment)
I have been following this convention thus far: std::string line; while(std::getline(in,line)) { if(line.size() && line[0] =='#') continue; /* parse text*/ } The obvious drawback is that comment may not begin at the first character, in the case of leading whitespace. What is the good way to deal with th...
Simple enhancement: you may want to use line.find_first_not_of(" ") to get the first non-whitespace and then check if that is a '#'. That would also cover to the zero length case. Something like this fragment: found= line.find_first_not_of(" \t"); if( found != string::npos) { if( line[found] == '#') co...
1,588,970
1,589,081
How to determine where code spends a lot of time in a kernel space (system calls)
I noticed that 10% my code run is system space. However I do NOT know which system calls. I suspect, though, it is either has to do files or timestamps. Is there a tool to figure out which system calls are the culprits? Also, I want to know the frequency of (and location) of calls (and callee) . I am on AS3 thx
Both strace and truss will help you see which system calls are taking time. Two useful options for strace are: -T to show the time spent in each system call, -c to summarize syscall counts, calls, error counts as a table. The two options are mutually exclusive though. You may want a full system profiling tool, to al...
1,588,976
1,589,073
Do pointers to string literals remain valid after a function returns?
Is the pointer returned by the following function valid? const char * bool2str( bool flg ) { return flg ? "Yes" : "No"; } It works well in Visual C++ and g++. What does C++ standard say about this?
On storage duration: 2.13.4 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration read in conjunction with 3.7.1 3.7.1. All ...
1,589,235
1,589,254
How to make functions with flag parameters? (C++)
How could I make a function with flags like how Windows' CreateWindow(...style | style,...), for example, a createnum function: int CreateNum(flag flags) //??? { int num = 0; if(flags == GREATER_THAN_TEN) num = 11; if(flags == EVEN && ((num % 2) == 1) num++; else if(flags == ODD && ((num...
You can define an enum specifying "single bit" values (note that the enclosing struct is acting here only as a naming context, so that you can write e.g. MyFlags::EVEN): struct MyFlags{ enum Value{ EVEN = 0x01, ODD = 0x02, ANOTHER_FLAG ...
1,589,370
1,592,604
CComBSTR memory allocation
I have a "const char* str" with a very long string. I need to pass it from a cpp client to a .Net COM method which expects BSTR type. Currently I use: CComBSTR bstr = str; This has the following issues: Sometimes this line fails with out of memory message When I pass the bstr to the COM class it takes a lot of memory...
If a method is expecting a BSTR passing a BSTR is the only correct way. To convert char* to a BSTR you use MultiByteToWideChar() Win32 API function for conversion and SysAllocStringLen() for memory allocation. You can't get around that - you need SysAllocStringLen() for memory allocation because otherwise the COM serve...
1,589,425
1,589,469
Templated Stl Containers
template <class T> class container { typedef list<T> ObjectList; public: ~container () { for (typename ObjectList::iterator item = _Container.begin(); item != _Container.end(); item++) { if (*item) delete (*item) } } } how can i free the con...
You don't want to do that -- the container (ObjectList, in your case) owns the items it contains, so to delete them, you need to tell it what you want, as in: ObjectList.erase(item);. Since you're (apparently) deleting all the items, you might as well use: ObjectList.clear(); and skip using your explicit loop at all. T...
1,589,459
1,589,486
What is the point of `void func() throw(type)`?
I know this is a valid c++ program. What is the point of the throw in the function declarement? AFAIK it does nothing and isnt used for anything. #include <exception> void func() throw(std::exception) { } int main() { return 0; }
That is an exception specification, and it is almost certainly a bad idea. It states that func may throw a std::exception, and any other exception that func emits will result in a call to unexpected().
1,589,630
1,589,954
Assigning vector::iterator to char array post VS 2003
I am trying to get some C++ code originally written in Microsoft Visual Studio (VS) 2003 to compile under VS 2008 and I am having trouble finding an efficient solution to assigning a vector::iterator to the beginning of a char array. I know that iterators went from being a defined as a simple pointer type (T*) to a cl...
The proper solution would be to template FindNumMsgs such that it can work with either iterators or pointers (since pointers can be used as iterators just fine). Something like this: template <class T> int FindNumMsgs(T it, int count) { while(count--) { // do whatever it++; } return n; }
1,589,742
1,589,792
Size of 64-bit dll 50% larger than 32-bit
I have a VC++ project (2005) that generates both 32-bit and 64-bit dlls. The 32-bit dll is 1044 KB whereas the 64-bit version is 1620 KB. I'm curious why the size is so large. Is it just because of the larger address size, or is there a compiler option that I'm missing?
Maybe your code contains a lot of pointers. The Free Lunch Is Over .... (Aside: Here’s an anecdote to demonstrate “space is speed” that recently hit my compiler team. The compiler uses the same source base for the 32-bit and 64-bit compilers; the code is just compiled as either a 32-bit process or a 64-bit one. The 64...
1,589,854
1,589,976
Cast between function pointers
I am currently implementing a timer/callback system using Don Clugston's fastdelegates. (see http://www.codeproject.com/KB/cpp/FastDelegate.aspx) Here is the starting code: struct TimerContext { }; void free_func( TimerContext* ) { } struct Foo { void member_func( TimerContext* ) { } }; Foo f; MulticastD...
C++ Standard says in 13.4/7 that: there are no standard conversions (clause 4) of one pointer-to-function type into another. In particular, even if B is a public base of D, we have D* f(); B* (*p1)() = &f; // error void g(D*); void (*p2)(B*) = &g; // error Still you may be could use function adapter for storing po...
1,589,950
1,589,987
Initializer list *argument* evaluation order
So, the C++ standard requires that class members be initialized in the order in which they are declared in the class, rather than the order that they're mentioned in any constructor's initializer list. However, this doesn't imply anything about the order in which the arguments to those initializations are evaluated. I'...
C++ Standard 12.6.2/3: There is a sequence point (1.9) after the initialization of each base and member. The expression-list of a mem-initializer is evaluated as part of the initialization of the corresponding base or member. The order of the initialization is the one you specified in the question. Evaluation is part...
1,590,062
1,590,231
Stream from std::string without making a copy?
I have a network client with a request method that takes a std::streambuf*. This method is implemented by boost::iostreams::copy-ing it to a custom std::streambuf-derived class that knows how to write the data to a network API, which works great. This means I can stream a file into the request without any need to rea...
The reason you're having these problem is that std::string isn't really suited to what you're doing. A better idea is to use vector of char when passing around raw data. If its possible, I would just change everything to use vector, using vector::swap and references to vectors as appropriatte to eliminate all your cop...
1,590,106
1,591,607
Best way to pass char* to .Net
I want to pass a big char* from cpp to .Net (preferably using COM). What is the best way (in terms of memory)? If I use CComBSTR it takes a lot of memory both when creating the BSTR in CPP and especially when moving it to .Net inside the COM call.
You can pass a StringBuilder as an input parameter and the C++ code can write into that. From a FAQ on PInvoke: To solve this problem (since many of the Win32 APIs expect string buffers) in the full .NET Framework, you can, instead, pass a System.Text.StringBuilder object; a pointer will be passed by the marshaler int...
1,590,148
1,590,322
Vs2008 C++: how can I make recursive include directories?
I am including a complicated project as a library in C++ using Visual Studio 2008. I have a set of include files that are scattered throughout a very complicated directory tree structure. The root of the tree has around ten directories, and then each directory could have multiple subdirectories, subsubdirectories, e...
That's clearly not a good idea, really. These directories are a way to organize the code in logical groups. /web /include /web /stackoverflow /language-agnostic /algorithm /database /meta /bug /feature-request /src /local/ /include /local ...
1,590,270
1,590,334
GoogleMock - Matchers and MFC\ATL CString
I asked this question on the Google Group but I think I will get a faster response on here. I'm trying to use Google's Mocking framework to test my code. I am also utilizing their test framework as well. I'm compiling in VC9. I'm having issues matching arguments that are MFC\ATL CStrings. GMock says the objects are no...
Since you are not making a copy of the strings when they are passed to your method, do you really need to check their values? It should suffice to write the following expectation: CString szKey = _T("Some key"); CString szValue = _T("Some value"); EXPECT_CALL(myMock, myMethod(szKey, szValue)).WillOnce(Return(true)); ...
1,590,676
1,592,207
Detect if a computer is a NetApp filer? (Unmanaged C++)
What is the best way to detect if a computer on a network is a netapp filer? I have tried some general querying of the computers attributes, but nothing has stuck out.
SNMP is enabled by default on filers ( though it may later be disabled ). Info on the available MIB can be found here.
1,590,688
1,590,804
Class 'is not a template type'
What does this error mean? Generic.h:25: error: 'Generic' is not a template type Here's Generic. template <class T> class Generic: public QObject, public CFG, public virtual Evaluator { Q_OBJECT std::string key_; std::vector<std::string> layouts_; std::vector<std::string> static_widgets_; std::map<...
I'm not sure if this is your problem, but you can't subclass QObject with a template class. Here is more information about that.
1,590,702
1,590,714
How to receive feedback from a Windows MessageBox?
I know its possible to do something like this with Windows: MessageBox(hWnd, "Yes, No, or Cancel?", "YNCB_YESNOCANCEL); But how do I react to what the user pressed (like closing the window if they clicked "yes")?
MessageBox will return a integer referring to the button pressed. From the previous link: Return Value IDABORT Abort button was selected. IDCANCEL Cancel button was selected. IDCONTINUE Continue button was selected. IDIGNORE Ignore button was selected. IDNO No button was selec...
1,590,773
1,591,733
handling central data buffer for many processes in C++
I ran into the following problem and cannot decide how to proceed: I have a class, Reader, getting a chunk of data every 1/T seconds (actually the data is from video frames, 30 frames per second). The chunks are to be passed to several objects, Detectors that process the chunks and output a decision. However, the numb...
I think (also based on your comment to Maciek) you have to start by understanding the difference between threads and processes and how they can communicate. Regarding the design problem: Try to start with a simple design. for instance, using only threads and passing each of the subscribers a shared_ptr to the job usi...