question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,031,413
3,031,433
Bitwise operators and converting an int to 2 bytes and back again
My background is php so entering the world of low-level stuff like char is bytes, which are bits, which is binary values, etc is taking some time to get the hang of. What I am trying to do here is sent some values from an Ardunio board to openFrameWorks (both are c++). What this script currently does (and works well fo...
Write a function to abstract sending the data (I've gotten rid of your temporary variables because they don't add much value): void send16(int value) { //send both bytes Serial.print(value & 0xFF, BYTE); Serial.print((value >> 8) & 0xFF, BYTE); } Now you can easily send any data you want: send16(analogRead...
3,031,438
3,031,448
error: typedef name may not be a nested-name-specifier
I am trying to do something along the lines of this answer, and struggling: $ gcc --version gcc (GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu4) file.cpp:7: error: template argument 1 is invalid file.cpp:7: error: typedef name may not be a nested-name-specifier And the offending part of the file: template <class R, class C, cl...
Drop typename from typename T0 in typedef typename boost::add_reference<typename T0>::type> TC0; and probably drop the second angle bracket as well. I.e. typedef typename boost::add_reference<T0>::type TC0;
3,031,453
3,031,504
Way Cross Compile C/C++ code to run on Windows, Linux, and Mac OS?
Is there a way to take my C++ code and cross compile it to run on Windows, Mac OS, and Linux? Is there a tool to do this, or does it have to be manually compiled on each OS via Terminal/Cygwin?
You can cross compile with what is known as a cross-compiler. Mingw can be installed as such. I believe MacOS just uses g++ so you can probably make a cross compiler for it as well. Never done it myself. You can scour the web for directions. Here's the top link I got from google: http://linux.bytesex.org/cross-com...
3,031,489
3,031,495
Call C methods from C++/Java/C# code?
Many of today's programming languages are based on C; like C++, C#, Java, Objective-C. So could I call a C method from C++ code? Or call C from Java or C#? Or is this goal out of reach and unreasonable? Please include a quick code sample for my and everyone else's understanding.
C++,C#, Objective-C, and Java can all call C routines. Here are a few links that will give you an overview of the process needed to call C from each language you asked about. Calling C from Java Calling C from C++ Calling C from C# Calling C from Objective-C
3,031,491
3,031,552
Read number from text file using C++ stream
I have a text file like below 2 1 2 5 10 13 11 12 14 2 0 1 2 99 2 200 2 1 5 5 1 2 3 4 5 1 0 0 0 I want to read file line by line, and read the umbers from each line. I know how to use the stream to read a fixed field line, but what about the non-fixed line? Best Regards,
Use a stringstream. In outline: string line; while( getline( cin, line ) ) { // read each line: istringstream is( line ); int n; while( is >> n ) { // read each number in line // do something with each number: } }
3,031,605
3,031,696
Statically initialize anonymous union in C++
I am trying to statically initialize the following structure in Visual Studio 2010: struct Data { int x; union { const Data* data; struct {int x; int y; }; }; }; The following is fails with error C2440: 'initializing' : cannot convert from 'Data *' to 'char'. static Data d1; static Data d = {1,...
Can you do it by defining overloaded constructors? Untested code ahead: struct Data { int x; union { const Data* data; struct {int a; int b; } z; } y; Data() { x = 0; y.data = 0; y.z.a = 0; y.z.b = 0; } Data(int x_, Data* data_) ...
3,031,610
3,031,611
Simultaneous execution of both if and else blocks
In C or C++ if ( x ) statement1; else statement2; For what value of x will both statements be executed? I know we can execute if-else together like this: if(1){ goto ELSE; } else{ ELSE: } Is there any way, like a value? (Which I think is not possible. Asking because someone is arguing!)
for what value of x both statements will be executed? There is no such value: either the value evaluates to true (something != 0), or it evaluates to false) (0). No other possible values exist. I know we can execute if-else together like this: if(1){ goto ELSE; } else{ ELSE: } That works but it isn’t depending of t...
3,031,649
3,031,700
In c++ is there any Events/delegates/interfaces/notifications! anything?
Say i have these classes ViewA and ViewB In objective C using the delegate pattern I could do @protocol ViewBDelegate{ - (void) doSomething(); } then in ViewB interface: id<ViewBDelegate> delegate; then in ViewA implementation i set the delegate: viewB.delegate = self; and now I can call in doSomething from viewB ...
If I were you, I wouldn't use function pointers to accomplish this task. Leave this option to the gurus ;) In Boost, there is a beautiful library called signals. It makes your life easier! This is an example of usage: #include <iostream> #include <boost/bind.hpp> #include <boost/signal.hpp> using namespace std; using n...
3,031,751
3,031,786
Simple binary File I/O problem with cstdio(c++)
The c++ program below fails to read the file. I know using cstdio is not good practice but that what I am used to and it should work anyway. $ ls -l l.uyvy -rw-r--r-- 1 atilla atilla 614400 2010-04-24 18:11 l.uyvy $ ./a.out l.uyvy Read 0 bytes out of 614400, possibly wrong file code: #include<cstdio> int main(int argc...
I resolved the issue by initializing the pointer. Interestingly, reading fails instead of giving a segfault when you try to read into an uninitialized pointer, that was confusing.
3,031,871
3,031,883
determining if value is in range with 0=360 degree problem
I am making a piece of code for DirectX app. It's meaning is to not show faces that are not visible. Normaly it would be just using Z-buffer, but I'm making many moves and rotations of mesh, so I would like to not do them and save computing power. I will describe this on cube. You are looking from the front so you see ...
You mean to check if oRot differs from cRot at least by 90 degree? //integral if ((360 + cRot - oRot) % 360 >= 90) ... //floating point diff = abs(cRot - oRot); if (diff >= 90 && diff <= 270) ...
3,031,923
3,031,946
difference between erase and remove/remove_if algorithms?
What is really the difference between the algorithms remove and remove_if and the member function erase? Does both of them result in a call to the removed objects destructor?
No, std::remove_if will move the elements that don't match the predicate to the end of list and will return an iterator to the new "end". Erase will effectively drop the element (call the dtor) from the container. The difference is perfectly illustrated by the examples here and here.
3,031,971
3,033,321
I'm new to C++. Please Help me with the Linked List (What functions to add)?
DEAR All; Hi, I'm just beginner to C++; Please help me to understand: What functions should be in the Linked list class ? I think there should be overloaded operators << and >>; Please help me to improve the code (style, errors, etc,) Thanks for advance. Igal. Edit: This i...
0 should be NULL inline only in the case that you don't care that your code will be public, usually implementation puts in separate file Mylist.cpp file. Why your destructor virtual, do you have inheritance ? You can just define struct node instead separate class its better define your list for practice like in stl. h...
3,032,076
3,032,123
How to convert from string to a number, and vice-versa in C++?
DEAR All I'm new to the C++, so maybe someone can say what the proper way to write a function that gets a string char (represents number) and converts it to the integer number. For example : input : Sixty five, output: 65. Maybe it should use by cin.getline() ? Well, vice-versa is little bit simlper... Thanks for ad...
Here's an illustration of a key part of a solution: const char* digits[] = {"zero", "one", "two", ...}; const char* tens[] = {"ten", "twenty", "thirty", ...}; // Loop to compare input text tokens against above ... The idea is to simplify conversion from text to digits by using the array index for the corresponding te...
3,032,348
3,480,833
Boost Test dynamically or statically linked?
We use Boost statically linked with our app but now I want to use Boost Test with an external test runner and that requires the tests themselves to link dynamically with Boost.Test through the use of the required BOOST_TEST_DYN_LINK define. Is this going to be a problem or is the way Boost Test links completely unrelat...
I believe Boost Test does not depend on any other compiled libraries, so dynamically linking it while statically linking the other Boost libraries should not be a problem. Our linking rules don't show any dependency of Boost Test on anything other than headers, nor do the rules in the boost.jam file (though the latter...
3,032,386
3,039,119
glGenBuffers not defined?
I'm using windows and I notice that a lot of functions are grayed out because I guess #ifdef GL_GLEXT_PROTOTYPES is not defined. One of these is the VBO extension. Should I just define GL_GLEXT_PROTOTYPES? Otherwise how else can I use VBOs since im using OpenGL32.dll (I want my application to have no dll dependencies n...
I recommend that you use GLEW to get rid of that problem. It's a long story, but resuming, Windows' OpenGL library only exposes OpenGL 1.1 entry points, so all functions beyond that version are loaded with wglGetProcAddress. GLEW solves this problem by doing that. http://glew.sourceforge.net/ Just link to GLEW and GLU/...
3,032,421
3,032,456
On Memory Allocation and C++
And I quote from MSDN http://msdn.microsoft.com/en-us/library/aa366533(VS.85).aspx: The malloc function has the disadvantage of being run-time dependent. The new operator has the disadvantage of being compiler dependent and language dependent. Now the questions folks: a) What do we mean that malloc is run-ti...
a) In this case I think they're eliding "run-time library" to "run-time". In other words it depends on the implementation in your C library. b) Indeed new is C++ specific. HeapAlloc, etc are technically usable in C and C++. c) They can't be used to create C++ objects because they won't call constructors so the point is...
3,032,502
3,032,515
OpenGL 3 equivalent of GLUTesselator?
I was wondering, since things like display lists are now deprecated, I'm thinking the GLU polygon tesselator is probably also deprecated. What is the new and correct way of creating concave or complex polygons and complying with the new GL 3 standard? Thanks.
GLUT is not and was never a part of OpenGL. If you need this functionality then use another library that provides it and can use VBOs or write it yourself. Starting with OpenGL 4 there is also hardware tesselation support.
3,032,726
3,032,868
rand() generating the same number – even with srand(time(NULL)) in my main!
So, I'm trying to create a random vector (think geometry, not an expandable array), and every time I call my random vector function I get the same x value, though y and z are different. int main () { srand ( (unsigned)time(NULL)); Vector<double> a; a.randvec(); cout << a << endl; return 0; } using ...
The issue is that the random number generator is being seeded with a values that are very close together - each run of the program only changes the return value of time() by a small amount - maybe 1 second, maybe even none! The rather poor standard random number generator then uses these similar seed values to genera...
3,032,859
3,032,869
Performance Cost of a Memcopy in C/C++
So whenever I write code I always think about the performance implications. I've often wondered, what is the "cost" of using a memcopy relative to other functions in terms of performance? For example, I may be writing a sequence of numbers to a static buffer and concentrate on a frame within the buffer, in order to ke...
memcpy is generally optimized to maximize memory bandwidth of large copies. Of course, it's not as fast as avoiding a copy completely, and for short copies of fixed size, direct assignment may be faster since memcpy has extra code to deal with odd lengths. But when you need to copy a block of memory, it's hard to beat...
3,032,965
3,034,865
C++ program infile won't open in xcode?
alt text http://img638.imageshack.us/img638/5731/screenshot20100613at121.png Why does the c++ program produce the error shown? I'm especially confused since outfile opens without error yet infile displays the error? Both are defined in xcode exactly the same!! I've altering the "path type" setting without success. ...
In Xcode, expand the "Targets" node and find your target. Given what I've seen, it'll be the only one there. Next, right-click on your project and add a new "Copy Files" build phase. When the dialog box comes up, make sure you set the Destination to "Products Directory". The new build phase will appear beneath your ta...
3,033,058
3,033,226
a question in NS c++ programming
I added a new patch to my NS and I've seen these two errors. Does anyone know what I can do? error: specialization of 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _AlgorithmTime]' in different namespace from definition of 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with...
You could just specify the namespace of the template you are trying to specialize: namespace std { template<> bool std::less<AlgorithmTime>::operator()(const AlgorithmTime & t1, const AlgorithmTime & t2)const { ... } } But as Michael Burr points out, there's no reason to specialize std::less, if all you ...
3,033,329
3,033,379
Why are Python Programs often slower than the Equivalent Program Written in C or C++?
Why does Python seem slower, on average, than C/C++? I learned Python as my first programming language, but I've only just started with C and already I feel I can see a clear difference.
Python is a higher level language than C, which means it abstracts the details of the computer from you - memory management, pointers, etc, and allows you to write programs in a way which is closer to how humans think. It is true that C code usually runs 10 to 100 times faster than Python code if you measure only the e...
3,033,364
3,063,940
Visual C++ Compiler Option To Dump Class Hierarchy
Is there any compiler option in MS Visual C++ equivalent to GCC's -fdump-class-hierarchy? i.e. showing the virtual function table layout.
try cl.exe /d1reportAllClassLayout test.cpp The output is something like: class request_handlerAttribute size(8): +--- 0 | name 4 | sdl +--- class perfmonAttribute size(8): +--- 0 | name 4 | register | (size=3) +--- Found doing: + findstr /i ...
3,033,405
3,033,412
Is there any difference these two pieces of code?
#include<stdio.h> class A {public: int a; }; class B: public A {private: int a;}; int main(){ B b; printf("%d", b.a); return 0; } #include<stdio.h> class A {public: int a; }; class B: private A {}; int main(){ B b; printf("%d", b.a); return 0; } I ask because I get different errors: erro...
They are different. In the first instance, you are creating two instances of the variable 'a'. One in the base class, one in the child class. In both examples you can't get access to the variable. If you have: A *pA = new B(); pA->a; // This will refer to A::a, which is allowed as it was defined public. B *pB = new B(...
3,033,419
3,033,566
Re-ordering C++ template functions
In C++, I have a certain template function that, on a given condition, calls a template function in another class. The trouble is that the other class requires the full definition of the first class to be implemented, as it creates the second class and stores them and manages them in similar fashions. The trouble is th...
For your example, the fact that the classes have a template function makes no real difference; just have a forward reference to the Child class and put the definition of the CreateChild function after the declaration of the Child class: class Child; class Master { public: Child* CreateChild() ; template<typenam...
3,033,483
3,033,490
How can I construct or return the underlying deque from a stack?
I want to be able to convert a std::stack<> to a std::deque<>. Is there a straightforward conversion?
You'll need to do it manually: while (!stk.empty()) { deq.push_back(stk.top()); stk.pop(); }
3,033,583
3,033,630
Refactor C++ code to use a scripting language?
Background: I have been working on a platformer game written in C++ for a few months. The game is currently written entirely in C++, though I am intrigued by the possibility of using Lua for enemy AI and possibly some other logic. However, the project was designed without Lua in mind, and I have already written work...
Scripting languages are useful for things that might change frequently or be extended, and can afford the trade from speed. It wouldn't make sense to use a scripting language in your core libraries, because those are relatively static (all they do is process stuff over and over) and need to be quick. But for things lik...
3,033,593
3,033,628
C++ inheritance: scoping and visibility of members
Can you explain why this is not allowed, #include <stdio.h> class B { private: int a; public: int a; }; int main() { return 0; } while this is? #include <stdio.h> class A { public: int a; }; class B : public A{ private: int a; }; int main() { return 0; } In both the cases, we have one pub...
In both the cases, we have one public and one private variable named a in class B. No, thats not true. In the first case, you can't have two identifiers with the same name in the same scope. While in the second case, B::a hides A::a, and to access A::a you have to fully qualify the name: b.a = 10; // Error. You ...
3,033,807
3,033,815
What is the difference between these two uses of const in C++?
Possible Duplicate: what is the difference between const int*, const int * const, int const * What is the difference between A const * pa2 = pa1; and A * const pa2 = pa1; (I have some class A for example).
Read the type from right to left: A const * pa2 = pa1; pa2 is a pointer to a read-only A (the object may not be changed through the pointer) A * const pa2 = pa1; pa2 is a read-only pointer to A (the pointer may not be changed) This does not mean that A cannot change (or is actually constant) const is misleading, unde...
3,033,885
3,033,889
difference between containers
I'm a little bit confused, can somebody please explain the main difference between those types of containers: map list set array I'm asking about C++.
http://cplusplus.com/reference/stl/ Maps are a kind of associative containers that stores elements formed by the combination of a key value and a mapped value. Lists are a kind of sequence containers. As such, their elements are ordered following a linear sequence. Sets are a kind of associative containers that store...
3,033,969
3,034,407
Fastest python/C++ multimedia library
I'm using pyglet for my OpenGL based game but is it the fastest library out there which has a python wrapper? I could create a C++ extension and use any C++ multimedia library. Are there any C++ libraries that are worth investing time into or is it not worth the extra work? Thank you.
Pygame is a python wrapper for the SDL library, which is widely used in game developing and provides OpenGL, sound and input management. To my knowledge at least SDL is quite fast, and the wrapper just encapsulates the binary functionality for python usage. Depending on your usage you can accomplish high speed.
3,034,043
3,034,097
Include Obj-C++ header from C++ source file
Consider the followng situation: MacFont.h struct MacFont : Font { // ... NSFont* font; }; MacFont will be implemented in MacFont.mm FontEngine.cpp: #if defined(OS_MAC) #include "MacFont.h" #elif // ... #endif //... In order to make it compiling, I should rename FontEngine.cpp to FontEngine.mm but I'm not allow...
If you cannot change the filename, don't fret. Consult your compiler manual for an option to force the filetype, and tell the compiler that this file, regardless of extension, is an Objective-C++ file.
3,034,096
3,034,123
Linux, C++ audio capturing (just microphone) library
I'm developing a musical game, it's like a singstar but instead of singing, you have to play the recorder. It's called oFlute, and it's still in early development stage. In the game, I capture the microphone input, then run a simple FFT analysis and compare the results to typical recorder's frequencies, thus getting t...
PortAudio is a strange choice given the other options. I would personally abstract away from everything and use GStreamer. Audio can be a horrible mess on Linux (speaking as a long term sufferer). Letting Gstreamer deal with that lets you forget about it, move along and not have to think about it again. OpenAL is prob...
3,034,285
3,034,476
How does implementing multiple COM interfaces work in C++?
I am trying to understand this example code regarding Browser Helper Objects. Inside, the author implements a single class which exposes multiple interfaces (IObjectWithSite, IDispatch). His QueryInterface function performs the following: if(riid == IID_IUnknown) *ppv = static_cast<BHO*>(this); else if(riid == IID_IObj...
Yes, there are multiple v-tables, one for each inherited interface. The static_cast<> returns it. The compiler makes sure that common methods in the inherited interfaces are shared, it fills each v-table slot with the a pointer to the same function. So you only need one implementation of AddRef, Release, QueryInterf...
3,034,296
3,034,356
Const-Qualification of Main's Parameters in C++
The C++ standard mandates that all conforming implementations support the following two signatures for main: int main(); int main(int, char*[]); In case of the latter signature, would the addition of (top-level) const-ness break any language rules? For example: int main(const int argc, char** const argv); From my un...
This is a known issue in the Standard. Also see this usenet discussion on the topic.
3,034,477
3,034,911
C++ "if then else" template substitution
I would like to declare a template as follows: template <typename T> { if objects of class T have method foo(), then const int k=1 else if class has a static const int L then const int k=L else const int k=0; } How can I do this? In general, I would like a mechanism for setting static consts...
The outer part is of course quite easy. Use boost::mpl::if_ to decide which int_ type to return from your metafunction and then access the value in it. No big deal. The part where you try to find out if type X has a function f() is still fairly straight forward but unfortunately you'll not find a generic answer. Eve...
3,034,632
3,034,646
Inheritance inside a template - public members become invisible?
I'm trying to use inheritance among classes defined inside a class template (inner classes). However, the compiler (GCC) is refusing to give me access to public members in the base class. Example code: template <int D> struct Space { struct Plane { Plane(Space& b); virtual int& at(int y, int z) = 0;...
It should be a problem related to c++'s two-phase name lookup: http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Name-lookup.html#Name-lookup
3,034,686
3,034,694
Mathematics errors in basic C++ program
I am working with a basic C++ program to determine the area and perimeter of a rectangle. My program works fine for whole numbers but falls apart when I use any number with a decimal. I get the impression that I am leaving something out, but since I'm a complete beginner, I have no idea what. Below is the source: #inc...
Change all your int type variables to double or float. I would personally use double because they have more precision than float types.
3,035,035
3,035,100
initialization of objects in c++
I want to know, in c++, when does the initialization of objects take place? Is it at the compile time or link time? For ex: //file1.cpp extern int i; int j=5; //file2.cpp ( link with file1.cpp) extern j; int i=10; Now, what does compiler do : according to me, it allocates storage for variables. Now I want to know...
Actually there are different cases: global variables or static variables (not classes): these values are stored in an init section of the exe/dll. These values are created by the linker based on the compiled object files information. (initialization on loading + mapping the dll/exe into memory) local non static variab...
3,035,052
3,051,432
Festival TTS showing SIOD:ran out off storage message
i am designing a front end for Festival TTS using it's C++ API Everything is working fine in my programme but i have a problem that i am giving a drop down option to user to select other languages when user select a language from drop down then festival tts shows a message on console saying: SIOD:ran out of storage T...
This post (from the festival mailing list, 2007) suggests you may simply have to increase the heap to a size which can contain all the languages one might select. I don't know how they ended up resolving this problem (the conversation thread appears to end after this email), whether it frees the memory or whether it ke...
3,035,114
3,035,125
C++: use array of strings wrapped in namespace?
I got the following code, wishing to wrap a group of strings nicely in a namespace: namespace msgs { const int arr_sz = 3; const char *msg[arr_sz] = {"blank", "blank", "blank" }; msg[0] = "Welcome, bla bla string 1!\n"; msg[1] = "Alright, bla bla bla.."; msg[2] = "etc."; } The code inside works ...
You can define the array inside the namespace: // this is legal namespace msgs { const char *msg[] = {"blank", "blank", "blank" }; } What you can't do is have a statement outside of a function: // this is a statement, it must be inside a function msg[0] = "Welcome, lets start by getting a little info from you!\n";...
3,035,292
3,035,441
How to use an overloaded function as an argument of function template?
I think everyone has experience working with a code like the following: void fun(Type1&); void fun(Type2&); vector<Type1> vec; for_each(vec.begin(), vec.end(), fun); Of course that won't compile, because it's not clear which function to be passed. And what's your commonly-used solution to the problem? I know this ...
One solution is to use template function: template<typename T> void fun(T&); // specialize fun for Type1 and Type2 ... for_each(vec.begin(), vec.end(), fun<Type1>); The better way is to use functor with template operator(): struct fun { template<typename T> void operator()(T&) const; }; ... for_each(vec.begin(), v...
3,035,348
3,036,533
Consistency in placing operator functions
I have a class like this: class A { ...private functions, variables, etc... public: ...some public functions and variables... A operator * (double); A operator / (double); A operator * (A); ...and lots of other operators } However, I want to also be able to do stuff like 2 * A instead of only ...
So what you are saying is that because you must put some operators (the ones that don't have A as the first param) outside the class, maybe you should put them all there so people know where to find them? I don't think so. I expect to find operators inside the class if at all possible. Certainly put the "outside" ones ...
3,035,367
3,035,379
Can I assign a object to a integer variable?
Let say I have a object. I'm assigning that to an integer. MyClass obj1 = 100;//Not valid Let's say, I have a parameterized constructor which accepts an integer. MyClass(int Num) { // .. do whatever.. } MyClass obj1 = 100;//Now, its valid Likewise on any circumstance, does the vice-versa becomes valid?!. eg) in...
Yes, provided that the object is implicitly convertible to an int, either directly or through an intermediate object. E.g. If your class have a conversion operator int it would work: MyClass { public: operator int() const { return 200; } };
3,035,376
3,035,403
Convert char array to int array c++
I`m having problems converting a char array read from file to an int array. Maybe someone can help me. This is my code: char vectorPatron[67]; int iPatrones[67]; archivo = fopen("1_0.txt", "r"); for(i=0;i<67;i++){ fscanf(archivo, "%c", &vectorPatron[i]); printf("%c",vectorPatron[i]); } fclose(archivo); for(i=0;...
That's because atoi receives a null-delimited string, while you are passing it a pointer to a single char (both are essentially char *, but the intent and use are different). Replace the call to atoi with iPatrons[i] = vectorPatron[i] - '0'; Also, you can remove the vectorPatrons array, simply read into a single char i...
3,035,422
3,035,673
static initialization order fiasco
I was reading about SIOF from a book and it gave an example : //file1.cpp extern int y; int x=y+1; //file2.cpp extern int x; int y=x+1; Now My question is : In above code, will following things happen ? while compiling file1.cpp, compiler leaves y as it is i.e doesn't allocate storage for it. compiler alloca...
The initialization steps are given in 3.6.2 "Initialization of non-local objects" of the C++ standard: Step 1: x and y are zero-initialized before any other initialization takes place. Step 2: x or y is dynamically initialized - which one is unspecified by the standard. That variable will get the value 1 since the ot...
3,035,455
3,035,498
Printing the address of a struct object
I have a struct like this typedef struct _somestruct { int a; int b; }SOMESTRUCT,*LPSOMESTRUCT; I am creating an object for the struct and trying to print it's address like this int main() { LPSOMESTRUCT val = (LPSOMESTRUCT)malloc(sizeof(SOMESTRUCT)); printf("0%x\n", val); return 0; } ..and I ge...
%x expects an unsigned. What you're printing is a pointer. To do that correctly, you normally want to use %p. To be pedantically correct, that expects a pointer to void, so you'll need to cast it: printf("%p\n", (void *)val); In reality, most current implementations use the same format for all pointers, in which case ...
3,035,582
3,035,606
Static Variables in Overloaded Functions
I have a function which does the following: When the function is called and passed a true bool value, it sets a static bool value to true When the function is called and passed a string, if the static bool value is set to true, it will do something with that string Here is my concern -- will a static variable remain ...
No, it creates two separate static variables - one for each function. The name of any C++ function is made op of its apparent name and its parameter types, and the name of the static is (conceptually at least) tacked on to that. Rather than add yet another function, you could consider making the variable static with re...
3,035,609
3,035,694
C++/g++: Concurrent program
I got a C++ program (source) that is said to work in parallel. However, if I compile it (I am using Ubuntu 10.04 and g++ 4.4.3) with g++ and run it, one of my two CPU cores gets full load while the other is doing "nothing". So I spoke to the one who gave me the program. I was told that I had to set specific flags for g...
AFAIK there are no compiler flags designed to make a single-threaded application exploit parallelism (it's definitely a nontrivial operation), with the exception of parallelization of loops iterations (-ftree-parallelize-loops), that, still, must be activated carefully; still, even if there's no explicit threads creati...
3,035,614
3,035,909
Getting list of all existing vtables
In my application I have quite some void-pointers (this is because of historical reasons, application was originally written in pure C). In one of my modules I know that the void-pointers points to instances of classes that could inherit from a known base class, but I cannot be 100% sure of it. Therefore, doing a dyn...
I would like to investigate the first 4 bytes of the memory the void-pointer is pointing to, to see if this is the address of the valid vtable. You can do that, but you have no guarantees whatsoever it will work. Y don't even know if the void* will point to the vtable. Last time I looked into this (5+ years ago...
3,035,625
3,035,958
Coordinate confusion
I subclassed QGraphicsItem and reimplemented paint. In paint I wrote something like this for labeling the item: painter->drawText("Test",10,40); After some time I think It may be useful to handle labeling with seperate item. So I wrote something like this. QGraphicsTextItem *label = new QGraphicsTextItem("TEST",this)...
I assume that you are using the same font size and type in both cases. If the difference in position is very small the reason can be the QGraphicTextItem is using some padding for the text it contains. I would try to use QGraphicsSimpleTextItem that is not going to add fancy stuff internally and see if you still have t...
3,035,975
3,036,824
Best approach to synchronising properties across threads
I'm looking for some advice on the best approach to synchronising access to properties of an object in C++. The application has an internal cache of objects which have 10 properties. These objects are to be requested in sets which can then have their properties modified and be re-saved. They can be accessed by 2-4 thre...
Firstly, I think you are worrying about the wrong thing. How do you know locking or copying causes bottlenecks in your code? Critical sections are fairly lightweight and don't cause much overhead, or, at least, not as much as you think. Just use the most lightweight locking primitive available. If you anticipate your s...
3,036,027
3,036,182
Features that require Q_OBJECT macro in Qt 4 other than signal - slots mechanism
I am using Qt 4.5 in windows XP. I know we have to use Q_OBJECT macro for signal - slot connection mechanism. But besides that, is there are any other reasons to use the Q_OBJECT macro? I recently come to know that for some other meta-object features we require the Q_OBJECT declaration. What are those features beside t...
You can find all you need to know about when Q_OBJECT macro is needed here: http://doc.qt.digia.com/4.6/metaobjects.html In resume you need it for signals and slots, to use tr for translation, to retrieve class name in real time from a QObject, to know if it inherits from other class (instrospection) to set properties ...
3,036,134
3,036,589
Encrypting password in compiled C or C++ code
I know how to compile C and C++ Source files using GCC and CC in the terminal, however i would like to know if its safe to include passwords in these files, once compiled. For example.. i check user input for a certain password e.g 123, but it appears compiled C/C++ programs is possible to be decompiled. Is there anywa...
It is not recommended to keep any sensitive static data inside code. You can use configuration files for that. There you can store whatever you like. But if you really want to do that first remember that the code can be easily changed by investigating with a debugger and modifying it. Only programs that user doesn't ha...
3,036,221
3,036,990
SendMessage (F4) fails when sending it to window
Working with Visual Studio 6 (VC++ 6.0) I'm using an ActiveX datepicker control which I fail to show expanded by default (3006216). Alternatively I'm trying to send a keyboard message (F4) to my window to open up the control, but nothing happens when I do so... // try 1: use the standard window handle LRESULT result = ...
Okay - there's two approaches on this issue (thanks for all the help, guys!): First: Use "::SendMessage" with correct message AND correct handle: ::SendMessage(m_wndDatePicker.m_hWnd, WM_KEYDOWN, VK_F4, 0); Alternatively use "SendInput": // important: set focus to control first m_wndDatePicker.SetFocus(); INPUT ...
3,036,282
3,036,389
Corrupted mysql table, cause crash in mysql.h (c++)
i've created a very simple mysql class in c+, but when happen that mysql crash , indexes of tables become corrupted, and all my c++ programs crash too because seems that are unable to recognize corrupted table and allowing me to handle the issue .. Q_RES = mysql_real_query(MY_mysql, tmp_query.c_str(), (unsigned int) tm...
You need to check the return value of mysql_store_result() - it might be NULL. http://dev.mysql.com/doc/refman/5.0/en/mysql-store-result.html mysql_store_result() returns a null pointer if the statement didn't return a result set (for example, if it was an INSERT statement). mysql_store_result() also returns a...
3,036,284
3,036,332
Releasing memory from map. C++
std::map<int, int> * mp = new std::map<int, int>; for(int i = 0; i < 999999; i++){ mp->insert(std::pair<int, int>(i, 999999-i )); } p("created"); //mp->clear(); - doesn't help either delete mp; p("freed"); The problem is: "delete mp" doesn't do anything. To compare: std::vector<int> * vc = new std::vector<i...
The RAM used by the application is not a precise way to tell if the memory has been semantically freed. Freed memory is memory that you can reuse. Sometimes though, you don't observe this freed memory directly in what the OS reports as memory used by our app. You know that the memory is freed because the semantics of t...
3,036,300
3,036,328
Equivalent of C# 'as' command in C++?
In C# you can use as to convert a type or get null: Object o = Whatever(); String s = o as String; Is there a similar easy way to achieve this in C++? I'm using Visual Studio 2010, if that's important. [Update]: Remember, there is a very important difference between casting and using as. Casting (at least in C#) will...
In C++, this would be a dynamic_cast, if you had a hierarchy where Object is the parent and String is the child. Object * p = createMyObject(); String * s = dynamic_cast<String *>(p); if(s) { ... } Dynamic casting a pointer will return a pointer to the object if the cast is possible, or a null pointer if not. Also, ...
3,036,334
3,036,391
How do I dynamically allocate memory for arrays in Qt C++?
I'm having some issues in allocating memory for an array dynamically in C++ within Qt SDK ... Here's for I'm doing: int dx = 5; QPoint * qPoint; qPoint = new QPoint[dx+1]; However when I try to debug the code, the programs just crashes when it tries to execute the third line .... any clues ?
If you want to use Qt SDK properly you have to use QVector instead of C++ arrays or std arrays. You can use QVector as a pointer or not, it doesn't really matter since internally it will allocate the memory dynamically. For example: int dx = 5; QVector<QPoint> points; points.resize(dx + 1); You can also do: QVector<...
3,036,469
3,036,483
static initialization confusion
I am getting very confused in some concepts in c++. For ex: I have following two files //file1.cpp class test { static int s; public: test(){s++;} }; static test t; int test::s=5; //file2.cpp #include<iostream> using namespace std; class test { static int s; public: test(){s++;} static i...
They link because the linker knows almost nothing about the C++ language. However, if you do this, you have broken the One Definition Rule, and the behaviour of your program will be undefined. writing invalid code is not a good way of learning C++. Also, you seem to be having a lot of questions about static variables -...
3,036,565
3,036,576
GCC: Compile to assembly with clarified correspondence to code?
When you break into the debugger in VS and open the disassembly window, each assembly fragment is displayed below it's corresponding code section (more or less). GCC with -S outputs only the stripped down assembly. Is there an option in GCC to show some correspondence to the original code? Source code is C++.
Compile your code with gcc -g, then you can disassemble with objdump -S yourfile. this will give you a disassembly interspersed with the source.
3,036,773
3,036,779
How to not #include <windows.h>
Using MSVC2008, 32bit on 64bit system. I was once advised to never include windows.h as 'its a real monster and will slow down my compile times significantly'. I tried leaving it out and obviously get compile errors. I included windef.h to define all the DWORDs etc, but I quickly come unstuck knowing what else to defin...
Internally, windows.h respects many defines, like NOMINMAX or WIN32_LEAN_AND_MEAN. It reduces the times significantly.
3,037,076
3,037,108
How to encapsulate a WinAPI application into a C++ class
There is a simple WinAPI application. All it does currently is this: register a window class register a tray icon with a menu create a value in the registry in order to autostart and finally, it checks if it's unique using a mutex As I'm used to writing code mainly in C++, and no MFC is allowed, I'm forced to encapsu...
The answer is SetWindowLongPtr. It allows you to associate a void* with a given hWnd. Then, in the WndProc, you just extract said void*, cast, and call the member method. Problemo solvo. There's a few ups/downs with SetWindowLongPtr, you must call some other function to see the effects or somesuch BS, and Windows sends...
3,037,636
3,037,686
VERY strange stack overflow in C++ program
I wrote a program some time ago (Mac OS X, C++, SDL, FMOD) and it perfomed rather good. But lately I wanted to extend its functionality and added some more code to it. And now, when I run it and try to test the new functionality, the program crashes with SIGABRT. Looking into debugger, on function stack I see: _kill k...
It is not a stack overflow error. __stack_chk_fail is called when stack frame corruption is detected. The traditional way to smash the stack is a buffer overflow. The code that causes it is not in your snippet, it is in the dots. After updating the question with code from a comment: both the strcpy and the sprintf ...
3,037,846
3,037,894
Mapping integers to types using C++ template fails in a specific case
I am attempting to compile the following template based code in VC++ 2005. #include <iostream> using namespace std; /* * T is a template which maps an integer to a specific type. * The mapping happens through partial template specialization. * In the following T<1> is mapped to char, T<2> is mapped to long * ...
Since T3 in your template class depends on the template parameter, the compiler can't known for sure what T3::xType will refer to (that might depend on the actual type r in each instantiation T2<r>). To tell the compiler that T3::xType will be a type, you need to add the typename keyword: typedef typename T3::xType xTy...
3,037,946
3,115,993
how can i store xml in buffer using xmlite?
I'm trying to write xml data with XmlLite on buffer but couldn't got any api. writing a xml file works perfect but on a memory stream I can't figure i am working on follwong link api http://msdn.microsoft.com/en-us/library/ms752901(v=VS.85).aspx
You can use either SHCreateMemStream or CreateStreamOnHGlobal to create an memory stream. Here is the sample code for your reference: CComPtr<IStream> spMemoryStream; CComPtr<IXmlWriter> spWriter; CComPtr<IXmlWriterOutput> pWriterOutput; // Opens writeable output stream. spMemoryStream.Attach(::SHCreateMemStream(NULL,...
3,038,045
3,038,073
How does compiler understand the pointer type?
How does the C++ compiler understand the pointer type? As I know pointer has a size equal to WORD of the OS (32 or 64). So does it store some info in that 32 (or 64) bits about type? Just because you can not have a pointer on one type and assign to that pointer another pointer with a different type.
A pointer is usually just a memory address on x86 based architectures (I don't know about other architectures). The compiler enforces type safety with different pointers at compile time - since it makes no sense to assign a pointer-to-char to a pointer-to-int, for example, especially since the objects pointed to are d...
3,038,074
4,293,112
Parsing simple MIME files from C/C++?
I have searched the web for days now but I can't seem to find a good solution to my problem: For one of my projects I'm looking for a good (lightweight) MIME parser. My customer provides MIME formatted files (linear, no hierarchy) which contain 3-4 "parts". The application must be able to split those parts and process ...
It's been a while. So I'll just answer my own question. After spending some more time on this, I ended up writing my own implementation. MIME is quite simple indeed, and if you read the documentation, you have something up and running in a short time. However, I think there should be something like vMime, but open sour...
3,038,085
3,038,108
Get executing directory in C++
I have a .CAB file that runs as part of an installer process on a Windows CE box. The CAB is written in C++. The CAB file is ran twice as part of an upgrade process but in different locations at different times. How can I find out what directory the .CAB file is being executed from (executing directory) using C++ onl...
If by "C++ only" you mean without using Windows API, I don't think the standard library has a function to do that. If you can call a Win32 API, you just have to call GetModuleFileName() with NULL as the first parameter, and you will get the path of the current executable. Now, the problem is: we you run the .CAB, what ...
3,038,151
3,038,312
VSC++, virtual method at bad address, curious bug
This guy: virtual phTreeClass* GetTreeClass() const { return (phTreeClass*)m_entity_class; } When called, crashed the program with an access violation, even after a full recompile. All member functions and virtual member functions had correct memory addresses (I hovered mouse over the methods in debug mode), but this ...
Don't ever use C-style casts with polymorphic types unless you're seriously sure of what you're doing. The overwhelming probability is that you cast it to a type that it wasn't. If your pointers don't implicitly cast (because they cast to a base class, which is safe) then you're doing it wrong.
3,038,280
3,038,384
Convert void* representation of a dword to wstring
I am having dumb monday so my apologies for posting such a newbie-like question. I am using CRegKey.QueryValue to return a dword value from the registry. QueryValue writes the value into void* pData and the length into ULONG* pnBytes. Now there is a way of getting it from pData into a wstring probably via stringstream...
Why don't you use CRegKey::QueryDWORDValue instead? Then you could just swprintf_s to print it into a string (if you wish to).
3,038,302
3,038,539
Why do ZeroMemory, etc. exist when there are memset, etc. already?
Why does ZeroMemory(), and similar calls exist in the Windows API when there are memset and related calls in the C standard library already? Which ones should I call? I can guess the answer is "depends". On what?
In C and C++, ZeroMemory() and memset() are the exact same thing. /* In winnt.h */ #define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length)) /* In winbase.h */ #define ZeroMemory RtlZeroMemory Why use ZeroMemory() then? To make it obvious. But I prefer memset() in C or C++ programs.
3,038,336
3,038,415
Linux / C++: Get Internet IP Address (not local computer's IP)
How can I programmatically get the Internet IP address? 1) If the computer is directly connected to the Internet using a USB modem. 2) If the computer is connected to the internet via another computer or a modem/router. I there a way to do both? P.S. This link gives exactly the Internet IP, but how can I use it in my p...
You can write socket code to send an http request to that link. Under unix/linux/cygwin you can use system("wget http://www.whatismyip.com/automation/n09230945.asp"); then open the file "n09230945.asp" and read its contents. Here is an example of how to make the request using sockets (I modified an online example f...
3,038,351
3,038,546
Check whether a string is a valid filename with Qt
Is there a way with Qt 4.6 to check if a given QString is a valid filename (or directory name) on the current operating system ? I want to check for the name to be valid, not for the file to exist. Examples: // Some valid names test under_score .dotted-name // Some specific names colon:name // valid under UNIX OSes, b...
I don't think that Qt has a built-in function, but if Boost is an option, you can use Boost.Filesystem's name_check functions. If Boost isn't an option, its page on name_check functions is still a good overview of what to check for on various platforms.
3,038,375
3,038,525
Convert Decimal to ASCII
I'm having difficulty using reinterpret_cast. Lets just say right off the bat that I'm not married ot reinterpret_cast. Feel free to suggest major changes. Before I show you my code I'll let you know what I'm trying to do. I'm trying to get a filename from a vector full of data being used by a MIPS I processor I des...
If your strings are null-terminated, don't you want to do 10. while(temp[i]!=0) instad of 10. while(&temp[i]!=0) Not sure I understand the DataMemory structure though...
3,038,391
3,038,619
Function pointers usage
Possible Duplicate: How does dereferencing of a function pointer happen? Hi All, Why these two codes give the same output, Case 1: #include <stdio.h> typedef void (*mycall) (int a ,int b); void addme(int a,int b); void mulme(int a,int b); void subme(int a,int b); main() { mycall x[10]; x[0] = &addme; x...
I'll simplify your question to show what I think you want to know. Given typedef void (*mycall)(int a, int b); mycall f = somefunc; you want to know why (*f)(5, 2); and f(5.2); do the same thing. The answer is that a function name both represent a "function designator". From the standard: "A function designator i...
3,038,500
3,040,577
How to create a compact Qt4 vBoxLayout
I've got a vBoxLayout which contains 3 simple buttons, when I increase the size of the widget containing the layout, the spacing between the buttons increases. I would like to stop this behaviour and keep the buttons in a consistent and compact layout, regardless of the size of the parent widget. This is what I've got ...
You'll want to add a stretchable spacer to the layout: button_layout = new QVBoxLayout ; button_layout -> setSpacing(0); button_layout -> setContentsMargins(0,0,0,0); button_layout -> addStretch(); button_layout -> addWidget(button_1); button_layout -> addWidget(button_2); button_layout -> addWidget(button_3); This wo...
3,038,693
3,038,754
Using UIKit from C/C++
The questions might have been already asked, but I want to understand if iPhone's frameworks limited only to Objective-C use or it could also be accessed from C/C++ code? For example, is it possible to use standard iPhone controls from C/C++ code? Are standard classes like NSArray, NSSet accessible from C/C++ code? If ...
You can mix Objective C with C++. Just rename your source file to .mm. Some Foundation classes such as NSArray and NSSet are toll-free bridges to CoreFoundation objects like CFArray and CFSet. The latter is a pure C library that you can use without ObjC. UIKit is a pure Objective-C framework. You could use UIKit with ...
3,038,851
3,038,861
C++ Virtual Destructors
When creating prototype classes I lay out the destructor as such: virtual ~MyClass(); When finalizing the class in a library I noticed that I cannot add 'virtual'. Is this normal, and is virtual taken into consideration or am I do something wrong? For example; when I try to do this I get a compiler error: virtual MyCl...
The virtual keyword is only used as part of the member function declaration inside of the class definition. If the member function is defined outside of the class definition, the virtual keyword is not placed there.
3,039,133
3,039,177
Boost::Mutex & Malloc
I'm trying to use a faster memory allocator in C++. I can't use Hoard due to licensing / cost. I was using NEDMalloc in a single threaded setting and got excellent performance, but I'm wondering if I should switch to something else -- as I understand things, NEDMalloc is just a replacement for C-based malloc() & free...
Google's malloc replacement is quite fast, thread safe by default, and easy to use. Simply link it into your application at it will replace the behavior or malloc/free and new/delete. This makes it particularly easy to re-profile your app to verify the new allocator is actually speeding things up.
3,039,156
3,039,208
gcc c++ command line error-message parser
Are there any programs for parsing and displaying in a nice format the c++ error messages generated by gcc. I'm really looking for something like less that I can pipe my errors into that will collapse the template parameter lists by default, maybe with some nice highlighting so that my errors are actually readable. (...
STL Error Decryptor (AKA STLFilt) can help decode them. I've had mixed results.
3,039,308
3,039,351
Obtaining the Button Clicked after a Clicked() is emitted in Qt (C++)
I was wondering, once a clicked() is emitted by a button is there any way of finding out what button emitted it without overloading the click() function? (I have a bunch of buttons with almost the same function but different text, which is the defining element of each button). Thanks in advance!
Within your slot, you can call the sender() function to get the QObject that sent you the clicked() signal. It returns a QObject *. Use qobject_cast to cast the QObject * to QPushButton *. Documentation here.
3,039,328
3,039,354
Problem with "not declared in this scope" error
I've got: error a1 was not declared in this scope Can somebody please explain why this code causes that? quiz.h #ifndef QUIZ_H_ #define QUIZ_H_ #include "quiz.cpp" // I deleted this row // and wrote void quiz(int i); class A { private: int player; public: ...
You should not be including the .cpp file in the header. Remove: #include "quiz.cpp" Also, the default value in: A::A(int initPlayer = 0){ should be in the header file instead. And edit your question provide the names of all your files, so we can tell you how to compile and link them.
3,039,456
3,039,594
How to run multiple arguments in Cygwin
I've been trying to run a program that will invert the order of a string and to run it, I have to type a second argument in prompt. int main(int argc, char* argv[]) { string text = argv[2]; for (int num=text.size(); num>0; num--) { cout << text.at(num); } return 0; } e.g. ./program...
#include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { string text = argv[1]; for (int num=text.size() - 1; num >= 0; num--) { cout << text.at(num); } return 0; } You missed the includes and used string::at wrong. There are size() chars in t...
3,039,615
3,039,688
Exceptional C++[Bug]?
I have been reading Exceptional C++ by Herb Sutter. On reaching Item 32 I found the following namespace A { struct X; struct Y; void f( int ); void g( X ); } namespace B { void f( int i ) { f( i ); // which f()? } } This f() calls itself, with infinite recursion. T...
There's a subtle difference between a using declaration (using A::f) and a using directive (using namespace A). A using declaration introduces a name into the scope in which it is used so using A::f makes the call to f in the definition of B::f(int) ambiguous. A using definition makes members of the namespace visible i...
3,039,647
3,039,715
What does 'Conditional expressions can be only boolean, not integral.' mean?
What does 'Conditional expressions can be only boolean, not integral.' mean? I do not know Java and I know C++ deffenetly not enought to understend what it means.. Please help (found in http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html in Comparing C++ and Java item 7 sub item 1)
Conditional expressions are used by the conditional and loop control structures to determine the control flow of a program. // conditional control structure if (conditionalExpression) { codeThatRunsIfConditionalExpressionIsTrue(); } else { codeThatRunsIfConditionalExpressionIsFalse(); } // basic loop control s...
3,039,767
3,039,802
Learn C++ after learning C#
I'm developing a library in C# at the moment and recently bought a great book to help me out but the code snippets are in C++. Does anyone have a link to a site/PDF that'll give me a crash course in C++? (mainly the syntax rather than pros/cons etc) because I'll be developing in C# but things like ->, ::, &, **, are g...
May be too simple for you but http://www.cplusplus.com/doc/tutorial/ is a good place for people who have never seen code before to start.
3,039,823
3,039,870
boost::unordered_map is... ordered?
I have a boost::unordered_map, but it appears to be in order, giving me an overwhelming feeling of "You're Doing It Wrong". Why is the output to this in order? I would've expected the underlying hashing algorithm to have randomized this order: #include <iostream> #include <boost/unordered_map.hpp> int main() { boo...
While I can't speak to the boost internals as I'm not a C++ guy, I can propose a few higher-level questions that may alleviate your concerns: 1) What are the guarantees of an "unordered" map? Say you have an ordered map, and you want to create a map that does not guarantee ordering. An initial implementation may simp...
3,039,960
3,042,488
Boost::asio::endpoint::size() and resize()
I was reading the boost endpoint documentation and saw size() and resize() member funcs. the documentation says: Gets the underlying size of the endpoint in the native type. what does this size represent and where can it be used/resized ? thanks.
As the docs state, a boost::asio::ip::basic_endpoint is an object that: describes an endpoint for a version-independent IP socket. In this case, "endpoint" usually refers to an IP address and port. Depending on the OS and the protocol you're using, the "native" representation of the endpoint (the one used by the ...
3,039,986
3,040,154
What Parallel computing APIs make good use of sockets?
My program uses sockets, what Parallel computing APIs could I use that would help me without obligating me to go from sockets to anything else? When we are on a cluster with a special, non-socket infrastructure system this API would emulate something like sockets but using that infrastructure (so programs perform much ...
Are you familiar with the Message Passing Interface (MPI)? That's generally the way to go for scaling your code on parallel computers. As you noted it's not compatible with most socket APIs, but the benefits in scaling will almost certainly outweigh the costs in converting your code.
3,040,095
3,040,118
C++ vector and struct problem win32
I have a structure defined in my header file: struct video { wchar_t* videoName; std::vector<wchar_t*> audio; std::vector<wchar_t*> subs; }; struct ret { std::vector<video*> videos; wchar_t* errMessage; }; struct params{ HWND form; wchar_t* cwd; wchar_t* disk; ret* returnData; }; When I try to add my video str...
I would guess that either p or p->returnData is an uninitialized/invalid pointer. Also, this isn't causing your crash, but it will once you fix the current problem: beware of returning the pointer to a local variable. Once your function goes out of scope the local vector will be destroyed and &v will be an invalid poi...
3,040,125
3,042,874
How do I correlate build configurations in dependant vcproj files with different names?
I have a solution file that requires a third party library (open source). The containing solution uses the typical configuration names of "Debug" and "Release". The third-party one has debug and release configurations for both DLL and static libraries - their names are not "Debug" and "Release". How do I tell the solu...
In the IDE there is "configuration manager" where you can stick project configurations with solution configurations. Also there is "build dependencies" tool to choose which project should be compiled first.
3,040,140
3,040,241
protocol buffers with C++ client and C# back-end?
How do you connect C# back-end with a C++ front-end via HTTP or web-service equivalent?
There are three parts here; the server (sounds like C#), the client (sounds like C++) and the transport. Taking them separately, and starting with the most important: the transport: big decision here is what shape you want the data to be in. You mention protocol buffers, so we're talking binary - but that could be: a...
3,040,201
3,040,222
Specializing a template member function of a template class?
I have a template class that has a template member function that needs to be specialized, as in: template <typename T> class X { public: template <typename U> void Y() {} template <> void Y<int>() {} }; Altough VC handles this correctly, apperantly this isn't standard and GCC complains: explicit speci...
Very common problem. One way to solve it is through overloading template <typename T> struct type2type { typedef T type; }; template <typename T> class X { public: template <typename U> void Y() { Y(type2type<U>()); } private: template<typename U> void Y(type2type<U>) { } void Y(type2type<int>) {...
3,040,442
3,040,467
How do I convert byte to string?
Is there any fast way to convert given byte (like, by number - 65) to it's text hex representation? Basically, I want to convert array of bytes into (I am hardcoding resources) their code-representation like BYTE data[] = {0x00, 0x0A, 0x00, 0x01, ... } How do I automate this Given byte -> "0x0A" string conversion?
In C++, you can use stringstream, and ssprintf. Some compilers may have an itoa method that will convert an integer into its textual representation. These are portable functions. You can always add an integer to '0' to get a textual digit and likewise with 'A' and 'a'.
3,040,465
3,040,494
Program won't compile
So below I have a code in C++ that is supposed to invert the arguments in a vector, but not the sequence. I have listed my problems as sidenotes in the code below. The invert function is supposed to invert each argument, and then the main function just outputs the inverted words in same order For instance, program("on...
The problem is that normal[num] is a character. append() doesn't have an overload for characters. You can use inverted.push_back(normal[num]); See the string API. I should add a couple other notes: 0) Why are you returning int from invert()? inverted is a string, so you should return a string: `string invert(string n...
3,040,472
3,040,526
How to do HTTP transfers with MFC/C++?
How do you do HTTP transfers in MFC? Which library would you use to access HTTP resources in MFC?
See the MFC wrappers for the WinInet library.
3,040,475
3,040,692
question about smart pointers
I have this snippet of the code and I must write appropriate code with class A (constructor, destructor, copy constructor, operator =), my question is do I need write smart pointers if I want that this code will work perfectly, if no, can you explain where writing smart pointers will be useful, thanks in advance A *pa...
A smart pointer is not needed, as non of the operations following new can throw. You just need: A *pa1 = new A(a2); A const * pa2 = pa1; A const * const pa3 = pa2; delete pa1; If this isn't what you are asking about, please clarify your question.
3,040,480
3,040,706
C++ template function compiles in header but not implementation
I'm trying to learn templates and I've run into this confounding error. I'm declaring some functions in a header file and I want to make a separate implementation file where the functions will be defined. Here's the code that calls the header (dum.cpp): #include <iostream> #include <vector> #include <string> #include ...
The problem you're having is that the compiler doesn't know which versions of your template to instantiate. When you move the implementation of your function to x.cpp it is in a different translation unit from main.cpp, and main.cpp can't link to a particular instantiation because it doesn't exist in that context. Th...
3,040,484
3,040,556
Need help in optimizing a drawing code ...
I needed some help in trying to optimize this code portion ... Basically here's the thing .. I'm making this 'calligraphy pen' which gives the calligraphy effect by simply drawing a lot of adjacent slanted lines ... The problem is this: When I update the draw region using update() after every single draw of a slanted l...
As I understand you should find min and max of x and y processed in your for-loop and use them in update(QRect(QPoint(minX-5, minY-5), QPoint(maxX+5, maxY+5)).normalized());