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,040,498
3,070,102
Determine when using the VC90 compiler in VS2010 instead of VS2008?
Is there a (Microsoft-specific) CPP macro to determine when I'm using the VC9 compiler in Visual Studio 2010 as opposed to Visual Studio 2008? _MSC_VER returns the compiler version, so with VS2010 multi-targeting feature, I'll get the same result as with VS2008. The reason for wanting to know the difference is that I ...
It seems there is no solution, a custom macro works even if it isn't quite as elegant as I would like.
3,040,738
3,048,534
Good OpenGL tutorial for Linux/Ubuntu?
I'm looking for a good Ubuntu OpenGL tutorial for a friend who already knows how to use OpenGL in Windows. Can anyone recommend any?
OpenGL is the same in Linux, Windows and MacOSX, the difference is the windowing system. If you just want to get quickly into building multi-platform OpenGL applications, take a look at GLUT (open-source alternatives, Ubuntu comes with freeglut). GLUT is source-compatible between operating systems, so you can compile t...
3,040,750
3,040,767
How to set C++ environment variable in Linux ubuntu?
I just installed Ubuntu on my Virtualbox on Windows. I was trying to install cmake and the installation guide in the cmake website asked me to do the following steps ./bootstrap make make install But when I just did the ./bootstrap command I get the following list of errors, can anyone suggest me how I can set the C+...
Install the build-essential packages via apt. sudo apt-get install build-essential
3,040,868
3,040,875
question about copy constructor
I have this class: class A { private: int player; public: A(int initPlayer = 0); A(const A&); A& operator=(const A&); ~A(); void foo() const; }; and I have function which contains this row: A *pa1 = new A(a2); can somebody please explain what exactly is going on, when I call A(a2) compiler calls copy construct...
Assuming a2 is an instance of A, this calls the copy constructor. It will call operator new to get dynamic memory for the object, then it will copy-construct a new object into the memory, then return a pointer to that memory.
3,040,893
3,040,907
Passing template into boost function
template <class EventType> class IEvent; class IEventable; typedef boost::function<void (IEventable&, IEvent&)> behaviorRef; What is the right way for passing template class IEvent into boost function? With this code I get: error: functional cast expression list treated as compound expression error: template argumen...
boost::function needs a type, so you cannot pass it a template's name, it has to be a template instance. So either use a specific instance typedef boost::function<void (IEventable&, IEvent<SomeEventType>&)> behaviorRef; or put the whole thing itself into a template: template< typename EventType > struct foo { typed...
3,040,951
3,040,995
Drawing filled circles as one vertex array using OpenGL?
Is there a way to draw many filled circles using one vertex array. Is there a way to draw a circle with triangles? I basically have hundreds of circles far apart from each other that need to be drawn but I feeling calling the vertex pointer for each circle is inefficient. I'd rather make 1 call for all circles if possi...
Take a look at Instancing, that is esp. GL_EXT_draw_instanced For your convenience: http://www.opengl.org/registry/specs/EXT/draw_instanced.txt (Note: This extension requires at least GeForce 8 series. As an EXT, it should be supported by ATI/Intel as well, but I do not know the requirements there - Probably hardware t...
3,040,976
3,041,165
Linking to a C library compiled as C++
I'm in linker paradise now. I have a C library which only compiles in Visual C++ (it probably works in gcc) if: I compile it as C++ code Define __cplusplus which results in all the declarations being enclosed in extern "C" { } So, by doing this I have a static library called, say, bsbs.lib Now, I have a C++ project c...
If you declare them as extern C in the lib (which is unnecessary, if you're calling them from C++), then they must be extern C in your headers.
3,041,240
3,060,071
telnet client connection stops receiveing data, server is still sending
I'm Working in an embedded linux environment. it launches a telnet daemon on startup which watches on a particular port and launches a program when a connection is received. i.e. telnetd -l /usr/local/bin/PROGA -p 1234 PROGA - will output some data at irregular intervals. When it is not outputting data, every X perio...
The first thing I would do is get out Wireshark and try to find out if the server is truly sending the message. It would be instructive to run Wireshark at the server as well as third party PC. Is there anything different about the last heartbeat? Edit. Well, that was an interesting find on your client. It seems lik...
3,041,249
3,041,264
When are temporaries created as part of a function call destroyed?
Is a temporary created as part of an argument to a function call guaranteed to stay around until the called function ends, even if the temporary isn't passed directly to the function? There's virtually no chance that was coherent, so here's an example: class A { public: A(int x) : x(x) {printf("Constructed A(%d)\n"...
Temporary objects exist up until the end of the full expression in which they are created. In your example, the A object created by A(4) will exist at least until the expression ends just after the return from the call to foo(). This behavior is guaranteed by the language standard: Temporary objects are destroyed as...
3,041,262
3,146,626
Most efficient way to draw circles for polygon outlines
I'm using OpenGL and was told I should draw circles at each vertex of my outline to get smoothness. I tried this and it works great. The problem is speed. It crippled my application to draw a circle at each vertex. I'm not sure how else to fix the anomaly of my outlines other than circles, but using display lists and t...
One (perhaps too fancy) alternative is to draw a single polygon that bounds the circle (say, a quad), and then use a fragment program to discard the fragments. This would not be entirely trivial to write, but I would bet it's the fastest way. You would simply pass the circle parameters to the fragment program and disca...
3,041,312
3,042,193
fastest way to crawl recursive ntfs directories in C++
I have written a small crawler to scan and resort directory structures. It based on dirent(which is a small wrapper around FindNextFileA) In my first benchmarks it is surprisingy slow: around 123473ms for 4500 files(thinkpad t60p local samsung 320 GB 2.5" HD). 121481 files found in 123473 milliseconds Is this speed nor...
There are some circumstances where such a speed is normal yes. First, using FindFirstFileA instead of FindFirstFileW is going to incur overhead for the conversion from UTF-16 to ANSI. Second, if you are going through directories that have not yet been accessed by the operating system, you will incur at least one seek p...
3,041,329
3,041,349
C++: Keep track of times function is called
Keeping track of how many times a function is called is easy when passing the counter as an argument into the function. It's also easy when returning a one from the called function. But, I do not want to go that route. The reason behind this is because it seems like bad programming (letting the function know too muc...
Have a static variable in your function and keep incrementing it each time the function in called. void my_Function(void) { static unsigned int call_count = 0; call_count++; } If you want to do it for debugging reasons, then there are tools like gcov which do this for you. (I'm pretty sure Microsoft doesn't ha...
3,041,408
3,041,414
Printing escape character
When I am given "d""\"/""b", I need to print out the statement character for character. (d, b, a slash, a backslash, and 5 quotes) in C++. The only errors that show now are the lines if(i.at(j)="\\") and else if(i.at(j)="\""). Also, how should the outside double apostrophes be excluded? #include <iostream> #include ...
You've goofed up your equality testing (==, not =). Also, start at index 1, and go until 1 less (2 less, by index) than the length of the string.
3,041,493
3,041,512
Can't convert from 'int' to 'int *'
So I have these lines of code: int maxY, maxX; getmaxyx(stdscr, &maxY, &maxX); It gives me the following error: error C2440: '=' : cannot convert from 'int' to 'int *' Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast twice for each time I use it. I'm...
getmaxyx is a macro, which doesn't take int*, but int. It resolves to something like getmaxyx(S,Y,X) -> X=s->X, Y=s->Y try getmaxyx(stdscr, maxY, maxX); // without the & operator see http://opengroup.org/onlinepubs/007908775/xcurses/getmaxyx.html
3,041,507
3,041,542
Any way to display C++ on a webpage?
Is there a relatively easy way to display the output of a C++ program on a webpage? And I don't mean manually, in other words, you see it on a webpage as it runs not as in I make a code tag and write it in myself. EDIT: Just so everybody can get this clear I am going to post this up here. I am NOT trying to make a webp...
Step one, get yourself a server-side language. Be that PHP, ASP, Python, Ruby, whatever. Get it set up so you can serve it. Step two, find your language's exec equivalent. Practically all of them have them. It'll let you run a command as if it were from the command line, usually with arguments and capture the output. H...
3,041,672
3,041,685
In this example where is the C++ assignment operator used rather than the copy constructor?
As part of an ongoing process of trying to upgrade my C++ skills, I am trying to break some old habits. My old school C programmer inclination is to write this; void func( Widget &ref ) { Widget w; // default constructor int i; for( i=0; i<10; i++ ) { w = ref; // assignment operator /...
Of course the copy constructor runs 10 times! When you iterate the for(;;) cycle, at each iteration the variables declared inside the braces will go out of scope. If Widget has a destructor, it will be called 10 times (possible performance hit).
3,041,673
3,041,734
no match for operator= using a std::vector
I've got a class declared like this: class Level { private: std::vector<mapObject::MapObject> features; (...) }; and in one of its member functions I try to iterate through that vector like this: vector<mapObject::MapObject::iterator it; for(it=features.begin(); it<features.end(); it++) { /* loop c...
I'd guess that this part of the error describes your problem: (const yarl::level::Level*)this Is the member function in which this code is found a const-qualified member function? If so, you'll need to use a const_iterator: vector<mapObject::MapObject>::const_iterator it; If the member function is const-qualified, t...
3,041,680
3,041,689
How to avoid integer overflow?
In the following C++ code, 32767 + 1 = -32768. #include <iostream> int main(){ short var = 32767; var++; std::cout << var; std::cin.get(); } Is there any way to just leave "var" as 32767, without errors?
Yes, there is: if (var < 32767) var++; By the way, you shouldn't hardcode the constant, use numeric_limits<short>::max() defined in <limits> header file instead. You can encapsulate this functionality in a function template: template <class T> void increment_without_wraparound(T& value) { if (value < numeric_limits...
3,041,759
3,041,786
Template problems: No matching function for call
I'm trying to create a template class, and when I define a non-member template function, I get the "No matching function for call to randvec()" error. I have a template class defined as: template <class T> class Vector { T x, y, z; public: //constructors Vector(); Vector(const T& x, const T& y, const T& z); Vector(con...
You defined your randvec as a function template, yet no function parameters depend on template parameter T (in fact randvec has no function parameters at all). This immediately means that it is impossible for the compiler to deduce the template argument T from the call to randvec(). You have to specify the template arg...
3,041,811
3,041,817
Pointer to 2D array. Why does this example work?
I have this code example, but I don't understand why changing the values in the array inside outputUsingArray() are changing the original array. I would have expected changing the values of the array in outputUsingArray() would only be for a local copy of the array. Why isn't that so? However, this is the behaviour I ...
passing int[] is really passing the pointer to the first element of the array. passing int* is passing the pointer to the first element of the array as well. They're identical. Since they're both pointing towards the same part of memory, changing one will change the other one.
3,041,890
3,041,899
C++: Unknown pointer size when forward declaring (error C2036)
In a header file, I have forward declared two members of a namespace: namespace Foo { struct Odp typedef std::vector<Odp> ODPVEC; }; class Bar { public: Foo::ODPVEC baz; // C2036 }; The error generated by the compiler is: error C2036: 'Foo::Odp *': unknown size I'm guessing this is an issue with forward...
Don't forward declare Odp. The compiler does not know what the type of std::vector<Odp> is, because Odp isn't yet declared. Give the compiler a full declaration for that class.
3,041,897
3,041,941
Sorting a 2 dimensional array on multiple columns
I need to sort a 2 dimensional array of doubles on multiple columns using either C or C++. Could someone point me to the algorithm that I should use or an existing library (perhaps boost?) that has this functionality? I have a feeling that writing a recursive function may be the way to go but I am too lazy to write out...
You can use std::sort (C++) or qsort (C or C++) to perform the sorting operation. The tricky part is that you need to define a custom comparison function for comparing your rows. For example: bool compareTwoRows(double* rowA, double* rowB){ return ( (rowA[0]<rowB[0]) || ((rowA[0]==rowB[0])&&(rowA[1]<rowB[1])) ); ...
3,041,925
3,041,967
Is Objective-C++ a totally different language from Objective-C?
As the title says... are they considered different languages? For example if you've written an application using a combination of C++ and Objective-C++ would you consider it to have been written in C++ and Objective-C, C++ and Objective-C++ or all three? Obviously C and C++ are different languages even though C++ and C...
Objective-C++ simply allows Objective-C and C++ code to be mixed (with caveats). It's not really a language on its own so much as a mechanism for allowing the two languages to intermix.
3,041,946
3,041,989
How to integer-divide round negative numbers *down*?
Seems like whenever I divide a negative int by a positive int, I need it to round down (toward -inf), not toward 0. But both C# and C++ round toward 0. So I guess I need a DivideDownward() method. I can write it in a few lines with a test for negative and so on, but my ideas seem klugey. So I'm wondering if I'm missing...
Note: this post produces incorrect results for input with a=-1. Please see other answers. [c++] This is probably what you meant by 'kludgey', but it's what I came up with. int divideDown(int a, int b){ int r=a/b; if (r<0 && r*b!=a) return r-1; return r; } In the if statement, I put r<0 - however I...
3,041,959
3,041,980
Life Scope of Temporary Variable
#include <cstdio> #include <string> void fun(const char* c) { printf("--> %s\n", c); } std::string get() { std::string str = "Hello World"; return str; } int main() { const char *cc = get().c_str(); // cc is not valid at this point. As it is pointing to // temporary string internal buffer, a...
See this question. The standard guarantees that a temporary lives until the end of the expression of which it is a part. Since the entire function invocation is the expression, the temporary is guaranteed to persist until after the end of the function invocation expression in which it is a part.
3,041,960
3,048,930
Filling in gaps for outlines
I'm using an algorithm to generate quads. These become outlines. The algorithm is: void OGLENGINEFUNCTIONS::GenerateLinePoly(const std::vector<std::vector<GLdouble>> &input, std::vector<GLfloat> &output, int width) { output.clear(); if(input.size() < 2) { return; } int temp; ...
EDIT: See my other answer. Add a triangle connecting the "outside" (check the sign of the 2D 'cross product') vertexes with the center joint vertex. If you want to get fancier you can do a 2D slerp to get a more rounded outer join, though this does cost correspondingly more triangles. Also, if you're going to use line...
3,041,984
3,042,007
Where to begin with multi-threaded programming with c++?
I'm trying to implement my own IRC client as a personal proejct and I realized I needed a way to read and write from the socket at the same time. I realized I could have a reading thread which reads from the socket in the background and puts data in a queue and I could have another thread which writes data from a queue...
For C++ threads, boost::thread (which is the basis for the upcoming std::thread) is the best way to go. That said, while threads might be the correct solution for your particular case, I just wanted to throw it out there that select and non-blocking sockets are a common approach to interleaving the reading/writing and ...
3,042,146
3,042,546
boost::bind breaks strict-aliasing rules?
Using Boost 1.43 and GCC 4.4.3, the following code boost::bind(&SomeObject::memberFunc, this, _1)); Generates the following warning boost/function/function_base.hpp:321: warning: dereferencing type-punned pointer will break strict-aliasing rules What's the correct way to eliminate these warnings without settin...
Are you sure that you've got the right object matched with the class that the member function foo is in? In other words, in the code you posted, is the type of *this the same as SomeObject? Aliasing occurs when the compiler has to track multiple pointers of different types to the same raw data, which is why I suspect t...
3,042,160
3,042,223
What's wrong with my code? (pdcurses/getmaxyx)
It gives me an access violation on the getmaxyx line (second line in the main function) and also gives me these two warnings: LINK : warning LNK4049: locally defined symbol "_stdscr" imported LINK : warning LNK4049: locally defined symbol "_SP" imported Yes, it's the same code as in another question I asked, it's just...
It has been a long time since I have used curses, but I would guess you need to call initscr() before any other curses call like getmaxyx. Also, you probably are also missing some error checking on the return of initscr and need to use the return values properly (perhaps you have to pass it on to other curses method?)...
3,042,191
3,042,224
Having trouble storing a CRTP based class in a vector
Im not sure if this can be done, im just delving into templates so perhaps my understanding is a bit wrong. I have a Platoon of soldiers, the platoon inherits from a formation to pick up the formations properties, but because i could have as many formations as i can think of I chose to use the CRTP to create the format...
C++ does not allow simple use of compile time and run time polymorphism. You are correct in that your vector is only able to hold one type. You're going to have to have your vector store a pointer to a non template type, or change the design to not use a vector. If you want to have the CRTP'd classes publicly inherit f...
3,042,249
3,042,266
Pure virtual destructor in interface
Here is my problem: I'm making a C++ DLL which relies extensively on instance object exports. So I return my actual instances as a pointers to an interface through some exported factory method. The interfaces I use are purely virtual, to avoid linking problems. So I need a pure virtual destructor too, and I implemente...
You shouldn't mix and match calls to new and delete across DLL boundaries. Instead, I'd recommend the tried-and-true method that COM uses: AddRef and Release. When the reference count hits zero, Release calls delete this; from inside the DLL, ensuring that new and delete are matched.
3,042,296
3,048,136
Tool used to retrieve code metrics in xUnit Test Patterns?
I'm reading xUnit Test Patterns by Gerard Meszaros. On one of the pages he refers to some software metrics: While the need to wrap lines to keep them at 65 characters makes this code look even longer than it really is, it is still unnecessarily long. It contains 25 executable statements including initializ...
Sorry to disappoint you but I did count by hand (well, by eye). It's only 25 lines of code! I just went through and counted semi-colons and subtracted lines that weren't acutally executed (like uninitialized variable declarations.) The point is not exactly how many lines of code there are but rather how much fewer line...
3,042,543
3,042,569
Porting Windows socket program to Unix: Alternative for winsock32 APIs in unix
In Socket Programming, how will a Unix thread receive a Socket CLOSE event from a client if connection is closed? Are there any API's which will notify the unix thread about the CLOSE event received? As in Windows we have WSAEnumNetworkEvents API which gets the event notification for a specified socket descriptor. What...
You can track the closure event when performing reading. The socket is closed when read returns 0 (talking about "Berkeley sockets" of course). //EDIT: Use poll or select to wait for some event to occur (data arrival, socket closure ...).
3,042,873
3,042,878
C++ pointers and constructors
Possible Duplicate: question about copy constructor if I have this snippet of the code A a1(i); A a2 = a1; A *pa1 = new A(a2); can somebody please explain what exactly the last line does, it makes copy of the a2 and pointer for this new object is pa1 or it just creates pointer for a2, thanks in advance
The last line creates a new object A, to which pa1 points, and its contents are the same as those of a2. I believe this example demonstrates the use of a constructor with arguments (first line), a copy constructor (second line) and another copy constructor (last line). In the end all the three object will have the same...
3,042,925
3,043,425
strange results with /fp:fast
We have some code that looks like this: inline int calc_something(double x) { if (x > 0.0) { // do something return 1; } else { // do something else return 0; } } Unfortunately, when using the flag /fp:fast, we get calc_something(0)==1 so we are clearly taking the wrong code path. This only happe...
I'm not familiar enough with FPUs to comment with any certainty, but my guess would be that the compiler is letting an existing value that it thinks should be equal to x sit in on that comparison. Maybe you go y = x + 20.; y = y - 20; y is already on the FP stack, so rather than load x the compiler just compares again...
3,042,972
3,043,000
transferring parameters in C++
can I have this snippet of the code: C *pa1 = new C(c2); and I transfer it to another function: foo(pa1); what exactly do I transfer actual pointer or its copy, thanks in advance and can somebody give some info about in which cases info is copied, and in which I transfer actual pointer declaration of foo: foo(A const...
Assuming foo is declared as: void foo(C* p); you are passing a copy of the pointer. This means, if foo does this: p = &some_other_object; that change to the pointer won't be seen by the caller. It also means we're copying the pointer, not the thing pointed to. If foo does this: p->bar = "Smurf!" pa1 in the caller wi...
3,043,214
3,043,318
How to define and use a friend function to a temlate class with the same template?
I have written the following code: #include <iostream> using namespace std; template <class T> class AA { T a; public: AA() { a = 7; } friend void print(const AA<T> & z); }; template <class T> void print(const AA<T> & z) { cout<<"Print: "<<z.a<<endl; } void main() { AA<int> a; print<int>(a); } And getti...
The problem is that when you do something like template<class T> class AA {friend void print(const AA<T>&);}; and you instantiate AA with like this AA<int> a; the friend declaration will be instantiated like friend void print(const AA<int>&); which is a non-template function! This means the compiler will not match t...
3,043,219
3,043,239
possible implementations of casting in c++
I have this snippet of the code in my header: class A { private: int player; public: A(int initPlayer = 0); A(const A&); A& operator=(const A&); ~A(); void foo() const; friend int operator==(const A& i, const A& member) const; }; implementation of the operator== int operator==(const A& i, const...
Your error is nothing to do with casting or user-defined conversions. You can't have a const qualification on a function that isn't a member function so this: int operator==(const A& i, const A& member) const; should be this: int operator==(const A& i, const A& member);
3,043,294
3,120,484
How to build a VS2010 C++ Project on a BuildServer
I've a .NET Solution with a managed C++ assemlby Targeting .NET 3.5 created with VS2010. The command: %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MyProject.sln compiles the solution on my dev machine. On my BuildServer I get this error: Build FAILED. "F:\CruiseControl.NET\Projects\MyProject\MyProject.sln"...
For now, installing VS 2010 is your only safe option. The Windows SDK will be updated to enable your scenario, but I don't have a specific release date. Until then, you'll need to install VS 2010 with the C++ tools in order to build your 2010 solution with C++ projects. Make sure you let the C++ team know about how dis...
3,043,339
3,043,387
Project Euler Problem #11
Source: http://projecteuler.net/index.php?section=problems&id=11 Quick overview: Take a 20x20 grid of numbers and compute the largest product of 4 pairs of numbers in either horizontal, vertical, or diagonal. My current approach is to divide the 20x20 grid up into single rows and single columns and go from there with ...
You know the grid is 20x20, so just paste it into a text file and read it like you would normally read a matrix: for (int i = 0; i < 20; ++i) for (int j = 0; j < 20; ++j) inFile >> mat[i][j]; Then do the obvious: for each element [i][j], go 4 elements down, 4 to the right, 4 diagonally to the right and 4 d...
3,043,487
3,043,590
Compile C++ code via C# class in Visual Studio
I use this method to compile C++ file in VS. But even i provide the correct file it returns false. Can any one help me... This is class called CL class CL { private const string clexe = @"cl.exe"; private const string exe = "Test.exe", file = "test.cpp"; private string args; public CL(String[] args) ...
In your Visual Studio installation folder there should be the following path: VC\bin\x86_amd64\1033\1033 There should be a clui.dll in this path. Copy it to the parent folder (VC\bin\x86_amd64\1033). This should solve your problem. I took the solution from http://connect.microsoft.com/VisualStudio/feedback/details/108...
3,043,519
3,043,551
How to const declare the this pointer sent as parameter
I want to const declare the this pointer received as an argument. static void Class::func(const OtherClass *otherClass) { // use otherClass pointer to read, but not write to it. } It is being called like this: void OtherClass::func() { Class::func(this); } This does not compile nad if i dont const declare the...
You cannot define static class memberv functions like this: static void Class::func(const OtherClass *otherClass) { // use otherClass pointer to read, but not write to it. } The function must be declared static in the class declaration, and then the function definition looks like: void Class::func(const OtherClas...
3,043,625
3,043,637
C++ Arrays of Structure access
I'm studying C++ from Schildt's book and don't quite understand what does he mean under third structure; Can somebody explain this -> To access a specific structure within an array of structures, you must index the structure name. For example, to display the on_hand member of the third structure, you would wri...
The third structure in an array of structures is the one placed in the third position in the array, i.e., the one with index 2. In your (ugly) code, invtry is declared as an array (of size SIZE) of structures of type type. Hence invtry[0] is the first element, invtry[1] the second, and invtry[2] the third - assuming, o...
3,043,971
3,044,450
Refactoring a leaf class to a base class, and keeping it also a interface implementation
I am trying to refactor a working code. The code basically derives an interface class into a working implementation, and I want to use this implementation outside the original project as a standalone class. However, I do not want to create a fork, and I want the original project to be able to take out their implementat...
The answer is, compiler overrides both functions, as can be shown by this sample: #include <cstdio> using std::printf; class A { public: virtual void a() { printf("A::a\n"); } }; class B { public: virtual void a() { printf("B::a\n"); } }; class C : public A, public B { public: virtu...
3,044,036
3,044,132
is this possible with activex controls?
I'm developing an Activex controller for IE7. I want to check version of flash+svg and install it if missing or old, and also change some settings in IE like setting up the printer to use landscape format.. I'm completly new to activex, so i'm trying to figure out how to do it, can you please post some pointers ? is w...
Starting with Windows Vista, IE7 will run in Protected Mode (unless User Account Control is disabled) so the browser will run in a sandbox with very low rights. It prevents exactly what you're trying to do. You can override it only if you have full control of the target systems (i.e. using policies) but in this case yo...
3,044,177
3,044,187
push_back private vectors with 2 methods, one isn't working
I have a class with a private vector of doubles. To access or modify these values, at first I used methods such as void classA::pushVector(double i) { this->vector.push_back(i); } double classA::getVector(int i) { return vector[i]; } This worked for a while until I found I would have to overload a lot of operators for...
You are returning the vector by value in your getVector(). This means that in your call "this->getClassA().getVector().push_back(first);", you copy the vector, then you push the element on the copy. The copy is then immediately discarded. In order to get it work the way you want, you need to return the vector by refere...
3,044,386
3,044,495
Segmentation fault on writing char to char* address
I've got problem with my little C program. Maybe you could help me. char* shiftujVzorku(char* text, char* pattern, int offset){ char* pom = text; int size = 0; int index = 0; while(*(text + size) != '\0'){ size++; } while(*(pom + index) != '\0'){ if(overVzorku(pom + index, patter...
Are you by any chance calling the code like this: shiftujVzorku( "foobar", "xx", 0 ); If so, your code attempts to write to a character literal, which is illegal in C. You should rather do: char buf[] = "foobar"; shiftujVzorku( buf, "xx", 0 );
3,044,484
3,044,539
Same socket getting created
I have this piece of code where a server socket is created and is set to listen on a particular port number say 5005. Now once the accept socket function returns the socket that gets created is copied into the m_Socket variable and finally i shutdown the server socket named SocServer which was created locally. Now my q...
Are you certain that the client who is connecting to your server did not close the connection? Also, you did not provide any function which uses the m_Socket so i cannot tell you if there is any problem while handling the incoming connection. I do not think that m_socket and SocServer may end up the same.
3,044,603
3,061,030
PDCurses TUI C++ Win32 console app - Access violation reading location
I have downloaded pdcurses source and was able to successfully include curses.h in my project, linked the pre-compiled library and all good. After few hours of trying out the library, I saw the tuidemo.c in the demos folder, compiled it into an executable and brilliant! exactly what I needed for my project. Now the pr...
Finally got it working. The solution was in the steps below: First I renamed tui.c to tui.cpp For the header tui.h, I followed the exact same step of wrapping the code as described here. then in my project i just included the header without any extern "C" block #include "tui.h" Compiled and it worked!
3,044,674
3,044,809
What is this (C/C++) program doing?
It's calling these API functions (advapi32.dll) with these parameters: CryptCreateHash ( 3275488, 32771, 0, 0, 1243424 ); CryptHashData ( 3203040, 'UY30930037661', 13, 0 ); CryptCreateHash ( 3276304, 32771, 0, 0, 46463812 ); CryptHashData ( 3203296, '-585164138661', 10, 0 ); CryptCreateHash ( 3276304, 32771, 0, 0, ...
(see here:) The call to CryptCreateHash initiates hashing with MD5 (32771 = 0x8003): CALG_MD5 0x00008003 MD5 hashing algorithm.. And the call to CryptHashData hashes the second parameter (the one in quotes) using that hash object. I guess these long strings could be keys that are to be hashed before transmission over ...
3,045,141
3,045,567
Okay to compare pointers returned by RUNTIME_CLASS() macro?
I've got a function that takes a list of CRuntimeClass pointers in order to setup a view. I'd like to return without doing anything if the function is called with a list of the same classes that are already setup. Saving the pointer values and comparing them on the next call is currently working, but I want to verify t...
Taking a peek at afx.h plus a little of debugging shows that RUNTIME_CLASS() returns a pointer to a static member: static CRuntimeClass class##class_name (as it can be seen in the definition of DECLARE_DYNAMIC(class_name) macro). As the member is static, the pointer to it does not change during runtime. In other words ...
3,045,188
3,049,374
Serialize boost array
I would like to serialize a boost::array, containing something that is already serializable. If get this error: error C2039: 'serialize' : is not a member of 'boost::array<T,N>' I have tried to include the serialization/array.hpp header but it did not help. Is there another header to include ? Thanks EDIT: Removed a w...
You need to show the code for the class contained in the boost::array. Since boost::array is STL-compliant, there should be no reason that this would not work. You should be doing something like the bus_route and bus_stop classes in this example. The class contained in the boost::array must declare boost::serializati...
3,045,418
3,045,435
Why is std::tr1::shared_ptr<>.reset() so expensive?
Profiling some code that heavily uses shared_ptrs, I discovered that reset() was surprisingly expensive. For example: struct Test { int i; Test() { this->i = 0; } Test(int i) { this->i = i; } } ; ... auto t = make_shared<Test>(1); ... t.reset(somePointerToATestObject); Tracing t...
In the general case, you can't reuse the existing ref count because there may be other shared_ptrs or weak_ptrs using it. If you can create somePointerToATestObject using make_shared(), then the implementation may use a single heap allocation for both the ref counts and the object. That will save you one of the heap a...
3,045,483
3,045,529
Resolving a Forward Declaration Issue Involving a State Machine in C++
I've recently returned to C++ development after a hiatus, and have a question regarding implementation of the State Design Pattern. I'm using the vanilla pattern, exactly as per the GoF book. My problem is that the state machine itself is based on some hardware used as part of an embedded system - so the design is fix...
You can define the member functions outside of the class definitions, e.g., class DL : public State { public: void Trigger2(); }; inline void DL::Trigger2() { new DH(); } Define the member functions that rely on later class definitions after those classes are defined. The inline keyword is only necessary if you ...
3,045,522
3,046,393
Best of both worlds: browser and desktop game?
When considering a platform for a game, I've decided on multi-platform (Win/Lin/Mac) but can't make up my mind as far as browser vs. desktop. As I'm not all too far in development, and now having second thoughts, I'd like your opinion! Browser-based games using Java applets: market penetration is reasonably high (for...
Yes you can have the best of both worlds. It's perfectly possible to write a Java application that will run in both an applet (for your online users) while also running as a standalone application in downloaded form. The key technologies are: JNLP JOGL for the graphics, which also has some good demos I'm not so famili...
3,045,602
3,045,653
Is C++ explicit conversion really that bad?
My knowledge of C++ at this point is more academic than anything else. In all my reading thus far, the use of explicit conversion with named casts (const_cast, static_cast, reinterpret_cast, dynamic_cast) has come with a big warning label (and it's easy to see why) that implies that explicit conversion is symptomatic ...
There're cases when you just can't go without it. Like this one. The problem there is that you have multiple inheritance and need to convert this pointer to void* while ensuring that the pointer that goes into void* will still point to the right subobject of the current object. Using an explicit cast is the only way to...
3,045,603
3,045,652
What does an object file contain?
During the various stages of compilation in C or C++, I know that an object file gets generated (i.e., any_name.o file). What does this .o file contain? I can't open it since it's a binary file. Could anybody please help me? Are the contents of the object file mainly dependent on the compiler which we use on Unix?
Object files can contain a bunch of stuff: Basically it's some or all of the list below: Symbol Names Compiled code Constant data, eg. strings Imports - which symbols the compiled code references (gets fixed up by linker) Exports - which symbols the object file makes available to OTHER object files. The linker turns ...
3,045,645
3,045,967
Precompiled headers question
I am right now reorganizing my project and what recently was a simple application now became a pair of C++ projects - static library and real application. I would like to share one precompiled header between two projects, but face some troubles with setting up the .pdb file paths. Assume my first project is called Libr...
The question is, why do you want to share the precompiled header (PCH) files. Generally I woul d say, that does not make sense. PCH are used to speed up compiling not to share any information between different projects. Since you also write about the PDB file, you probably want to debug the library code with your appli...
3,045,831
3,045,985
Sort List based on dynamically generated numbers in C++
I have a list of objects ("Move"'s in this case) that I want to sort based on their calculated evaluation. So, I have the List, and a bunch of numbers that are "associated" with an element in the list. I now want to sort the List elements with the first element having the lowest associated number, and the last having t...
I would suggest a Schwartzian transform sort. Make a new vector (I recommend vector for more efficient sorting) of pairs of the associated value, and a pointer to its item. Sort the vector of pairs and then regenerate the list from the sorted vector. Since operator< is defined on a std::pair to be comparison by the fir...
3,046,050
3,046,087
STL iterators - purpose
What is the purpose of STL iterators? Why have programmers created this concept at all?
Iterators allow you to separate algorithms from the container. As long as you have a start and end iterator, and know the capabilities of the iterator (random access etc) you can do operations on the range specified by the iterators. For example, see std::for_each, std::transform. This way you can implement just one ve...
3,046,359
3,046,479
Validity of a Socket
I have created a socket using the following lines of code and i get a valid socket and connection is established between the client and server machines. Is there a possibility that the socket becomes invalid due to network disturbances or any other reason. If so how do we check whether the socket is valid or not. S...
Pass your socket to any one of the windows socket functions (eg. getsockopt()), if the socket is invalid, it will return SOCKET_ERROR while WSAGetLastError() will return WSAENOTSOCK. It is important to note that INVALID_SOCKET does not equal 0(the actual value, which you should not use specifically is ((SOCKET)(~0))
3,046,598
3,047,879
buffer overflow with boost::program_options
I have a problem using boost:program_options this simple program, copy-pasted from boosts' documentation : #include <boost/program_options.hpp> int main( int argc, char** argv ) { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help", "...
I found the problem I was linking against libboost_program_options-vc80-mt.lib which wasn't the good library since I changed the runtime library to Multithread DLL.
3,046,624
3,046,740
How will the Windows C/Sleep() function operate during clock drift?
If I run something like Sleep(10000), and the system clock changes during that, will the thread still sleep for 10 seconds of wall-clock time, or less or more? I.e. does the Sleep() function convert milliseconds into hardware ticks?
Sleep() is independent of the wall-clock time. It is based on the same timer that is used for thread scheduling. You will mostly not sleep exactly 10 seconds though, due to the frequency of the system clock and when you actually get scheduled to run after the timeout elapses.
3,046,668
3,046,715
How to mute microphone in Windows 7 with C/C++?
I made a program to mute microphone using WinAPI and it seems to work perfectly in Windows XP but doesn't do a thing in Windows 7. Is it possible to control microphone volume or mute with WinAPI in Windows 7? void setVolume(DWORD volume) { HMIXER mixer; if (mixerOpen(&mixer, 0, 0, 0, 0) != MMSYSERR_NOERROR) { Mess...
You need to use the new audio APIs introduced by Windows Vista. Here is an example. *EDIT: Visual Studio 2015 (C++): Usange: // To 100% ConsoleApplication3.exe -f 1 // To 0% ConsoleApplication3.exe -f 0 // To 50% ConsoleApplication3.exe -f 0.50 Code: #include "stdafx.h" #include <stdio.h> #include <windows.h> #inc...
3,046,889
3,048,361
Optional Parameters with C++ Macros
Is there some way of getting optional parameters with C++ Macros? Some sort of overloading would be nice too.
Here's one way to do it. It uses the list of arguments twice, first to form the name of the helper macro, and then to pass the arguments to that helper macro. It uses a standard trick to count the number of arguments to a macro. enum { plain = 0, bold = 1, italic = 2 }; void PrintString(const char* messag...
3,046,964
3,047,278
#define far, #define near Windef.h
Possible Duplicate: Is there a clean way to prevent windows.h from creating a near & far macro? What's the point of these two defines in Windef.h? #define far /* nothing */ #define near /* nothing */ I know it has to do with near and far pointers and the fact they're no longer used, but, is it safe to #undef...
Don't reuse them. The last thing you need is to have to repeatedly explain to people that they aren't the old-school ornaments. If it is critical to your app, you might consider using capitalized versions (since identifiers are case sensitive) - the compiler will catch typos when you mess up. Just accept that this is c...
3,047,002
3,047,118
Two separate tm structs mirroring each other
Here is my current situation: I have two tm structs, both set to the current time I make a change to the hour in one of the structs The change is occurring in the other struct magically.... How do I prevent this from occurring? I need to be able to compare and know the number of seconds between two different times -- ...
You have to do this: struct tm* temp_tm; struct tm dispatchtime; // No longer a pointer struct tm uiuctime; // No longer a pointer temp_tm = dispatchtime_tm(); dispatchtime = *temp_tm; // Member to member copy temp_tm = uiuctime_tm(); uiuctime = *temp_tm; // Member to member copy This way you will keep a local c...
3,047,095
3,048,590
I'm having a problem identifying a floating point exception
I'm using c++ in visual studio express to generate random expression trees for use in a genetic algorithm type of program. Because they are random, the trees often generate (I'll call them exceptions, I'm not sure what they are) Thanks to a suggestion by George, I turned the mask _MCW_EM on so that hardware interrupts ...
Thanks to KennyTM for spotting the duplicate. A link in the link answered my query. I used: #include "limits.h" #include "math.h" bool isIndeterminate(const double pV) { return (pV != pV); }; bool isInfinite(const double pV) { return (pV >= DBL_MAX || pV <= -DBL_MAX); }; As KennyTM's response was a...
3,047,276
3,052,606
Profiling help required
I have a profiling issue - imagine I have the following code... void main() { well_written_function(); badly_written_function(); } void well_written_function() { for (a small number) { highly_optimised_subroutine(); } } void badly_written_function() { for (a wastefully and unnecessarily ...
That's usually known as a "callgraph profile", and I'm fairly sure Visual Studio will do that.
3,047,381
3,048,698
Boost signals and passing class method
I've defined some signal: typedef boost::signals2::signal<void (int temp)> SomeSig; typedef SomeSig::slot_type SomeSigType; I have some class: class SomeClass { SomeClass() { SomeSig.connect(&SomeClass::doMethod); } void doMethod(const SomeSig &slot); }; And got a lot of errors: error: ‘BOOST_PP_ENUM...
Both Pavel and Keith are correct (+1 for both). SomeSig is a type, you cannot call on a type. You must instantiate SomeSig. You also must provide a pointer to the object when using method function pointers. The _1 is a place holder required during a bind indicating that the method function pointer being bound requi...
3,047,410
3,047,440
How do I benefit from argc and argv in C++, the standard way?
What is the standard way to retrive and check for the argc and argv and what is the best usage and how to do that in linux? Please provide examples. "I want to have a complex command-line options and I want to use them in my application" That what I mean. Thanks
Please use boost program options http://www.boost.org/doc/html/program_options.html for access to the command arguments.
3,047,438
3,047,528
I want to make a wrapped acces type for certain internals of one of classes and I have some performance questions
I am writing an abstract matrix class (and some concrete subclasses) for use on very differing hardwares/architectures, etc. and I want to write a row and column type that provides a transparent reference to the rows and columns of the matrix. However, I want to tune for performance, so I'd like this class to be essen...
Design for efficiency golden rule number 1 is to really properly fully completely totally understand and appreciate all of the nuances of the environment in which you are working. Including, but not limited to: Understanding the costs of each compiler construct you are using Understand how the compiler uses memory Do ...
3,047,511
3,047,780
C++ private inheritance and static members/types
I am trying to stop a class from being able to convert its 'this' pointer into a pointer of one of its interfaces. I do this by using private inheritance via a middle proxy class. The problem is that I find private inheritance makes all public static members and types of the base class inaccessible to all classes under...
You should be able to access Base::Enum by fully qualifying it: class Child : public Middle { public: void Method() { ::Base::Enum e = ::Base::value; } }; This is the behavior specified by the language (C++03 §11.2/3): Note: A member of a private base class might be inaccessible as an inherited m...
3,047,567
3,047,593
Object allocation in C++
char *myfunc() { char *temp = "string"; return temp; } In this piece of code, where does the allocation of the object pointed to by temp happen and what would be its scope? Is this function a valid way to return a char* pointer?
Is the code correct? Yes your code is (almost) fine, because "string" is a string literal and located in static storage. Note: A pointer is just a variable which stores a memory address. This line simply stores the address of the string literal "string" inside a variable called temp. char *temp = "string"; The C++ sta...
3,047,646
3,047,662
How to use a "vector of vector"?
I already searched on the web for it but I didn't get satisfying results. I want to create something like vector< vector<int*> > test_vector; How do i fill this vector of vector? How to access it's members? Maybe someone knows some nice tutorials on the web? kind regards mikey
Just remember that each element of test_vector is of type vector<int*>. You would fill test_vector by filling each element vector. You can access this just like any multi-dimensional array. See: int *p = test_vector[0][0]; Or: int *p = test_vector.at(0).at(0);
3,047,753
3,051,260
How to convert a C++ program that uses CUDA into MEX
For work, I am converting the Image Denoising program that comes with the CUDA SDK into a MATLAB program. As far as I know, I have made all the necessary changes required by MATLAB, but when I try to call mex on it, MATLAB returns a bunch of linkage errors that I have no idea how to fix. If anyone has any suggestions o...
You need to link the CUDA libraries to your MEX file. It looks like you're also using some of the "cutil.h" stuff from the CUDA SDK (such as cutCheckCmdLineFlag), so you'll need to link against not only the cudart library, but also cutil. I.e. you probably need to add something like -Lc:\CUDA\lib -lcudart -lcuda -L<pat...
3,048,200
3,048,578
Maximum Width of a Printed Double in C++
I was wondering, how long in number of characters would the longest a double printed using fprintf be? My guess is wrong. Thanks in advance.
Who knows. The Standard doesn't say how many digits of precision a double provides other than saying it (3.9.1.8) "provides at least as much precision as float," so you don't really know how many characters you'll need to sprintf an arbitrary value. Even if you did know how many digits your implementation provided, t...
3,048,377
3,048,384
How to free memory in try-catch blocks?
I have a simple question hopefully - how does one free memory which was allocated in the try block when the exception occurs? Consider the following code: try { char *heap = new char [50]; //let exception occur here delete[] heap; } catch (...) { cout << "Error, leaving function now"; //delete[] hea...
Study the RAII idiom (Resource Acquisition Is Initialization)! See e.g. the Wikipedia article on RAII. RAII is just the general idea. It is employed e.g. in the C++ standard library's std::unique_ptr or std::shared_ptr template classes. Very brief explanation of the RAII idiom: Basically, it is the C++ version of try....
3,048,548
3,048,575
Why an auto_ptr can "seal" a container
auto_ptr on wikipedia said that "an auto_ptr containing an STL container may be used to prevent further modification of the container.". It used the following example: auto_ptr<vector<ContainedType> > open_vec(new vector<ContainedType>); open_vec->push_back(5); open_vec->push_back(3); // Transfers control, but now th...
The closed_vec pointer holds the type const vector<ContainedType>. Because the type is const, you can't call any methods on it that aren't also defined as const (which means they don't change internal data). Naturally push_back is non-const, as it changes the vector, so you can't call it on a const pointer. It doesn't ...
3,048,577
6,832,617
Dependency issue with MSBuild 4.0 when doing DllImport from C# into unmanaged C++ library
Explicitly setting dependency in VS2010 between unmanaged C++ project and C# project is honored in VS2010, but dependency is ignored in MSBuild 4.0. It is impossible to add a reference to unmanaged C++ project from C# project, afaik. How do i ensure correct build order if a solution contains unmanaged and managed proje...
MSBuild has a bug in it and doesn't correctly honor project dependencies added at the solution level. Take a look at http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/80cc6447-b720-4806-8395-7c257b207613/ and https://connect.microsoft.com/VisualStudio/feedback/details/613284/msbuild-4-does-not-respect-build-...
3,048,629
3,051,858
How to turn stream from Named Pipe into Socket Stream? (in C++ on Windows)
How to turn stream from Named Pipe into Socket Stream? (in on Windows) (Share all new data in pipe stream on socket)?
The nice thing of named pipes in Windows is that they already work in a network just specifying the server name in the: CreateFile("\\ServerName\pipe\PipeName", ... However, if this not fits your needs, you just have to build a read loop (I suggest OVERLAPPED I/O) that, at every read from the pipe, writes the received...
3,048,677
3,048,964
Access Violation reading elements of an array
I've written my own code to parse an .obj model file - essentially just ASCII text. The file gets parsed and stored in the class correctly according to my tests. I can read back the values (from data members) just fine in the loading function. The problem occurs when I try to read back the values in my main rendering l...
I had typed up some silly response which I realized wasn't right...but I had to keep thinking on it, and I came up with another idea. Where is this object being assigned? Your code isn't clear if data and _data are the same object or not, but I noticed that your method there seems to return _data as an object. I'm led ...
3,048,689
3,048,749
Self referential type
What type T makes the following code compilable? T f(){ return &f; } I'd prefer a C answer, but I marked the question as C and C++ in case there is only an answer using templates.
I hope this isn't cheating (C++ only): class T { private: T (*_func)(); public: T(T (*func)()) : _func(func) {} T operator()() { return *this; } }; T f() { return &f; } int main() { f()()()()()()()(); }
3,048,761
3,048,799
Howto mix TDD and RAII
I'm trying to make extensive tests for my new project but I have a problem. Basically I want to test MyClass. MyClass makes use of several other class which I don't need/want to do their job for the purpose of the test. So I created mocks (I use gtest and gmock for testing) But MyClass instantiate everything it needs i...
You mock it the same way you'd mock any other class. Have the RAII class' constructor take care of it. class MyInterface { virtual void MyApiFunction(int myArg) { ::MyApiFunction(myArg); } }; class MyRAII : boost::noncopyable //Shouldn't be copying RAII classes, right? { MyInterface *api; publi...
3,048,809
3,048,938
error in C++, within context
I received homework to make program without casting using constructors so this is my code, I have two classes: class Base { protected: int var; public: Base(int var = 0); Base(const Base&); Base& operator=(const Base&); virtual ~Base(){}; virtual void foo(); void foo() const; operator in...
You can only access protected members from another object if that object is of the same type as the object that is trying to access it. In your example the constructor and assignment operator both take in a const Base& so there is no guarantee that the actual object will be of type Derived.
3,048,946
3,232,123
Recommendations for a C++ polymorphic, seekable, binary I/O interface
I've been using std::istream and ostream as a polymorphic interface for random-access binary I/O in C++, but it seems suboptimal in numerous ways: 64-bit seeks are non-portable and error-prone due to streampos/streamoff limitations; currently using boost/iostreams/positioning.hpp as a workaround, but it requires vigil...
I just ended up going with a set of abstract interfaces similar to what I outlined in the question. There don't seem to be any lightweight, polymorphic standards for this...
3,049,123
3,050,142
strcmp() but with 0-9 AFTER A-Z? (C/C++)
For reasons I completely disagree with but "The Powers (of Anti-Usability) That Be" continue to decree despite my objections, I have a sorting routine which does basic strcmp() compares to sort by its name. It works great; it's hard to get that one wrong. However, at the 11th hour, it's been decided that entries which ...
In this special case with only uppercase letters (as mentioned by the OP in comments) and digits 0-9, you could also omit the order table and instead multiply both differing characters by 4 and compare the results modulo 256. The range of ASCII digits (48 to 57) will not overflow 8 bits (57 × 4 = 228), but the range of...
3,049,404
3,049,483
Apples, oranges, and pointers to the most derived c++ class
Suppose I have a bunch of fruit: class Fruit { ... }; class Apple : public Fruit { ... }; class Orange: public Fruit { ... }; And some polymorphic functions that operate on said fruit: void Eat(Fruit* f, Pesticide* p) { ... } void Eat(Apple* f, Pesticide* p) { ingest(f,p); } void Eat(Orange* f, Pesticide* p) { p...
When a question like this comes up, it's good to look at exactly why you want to make particular decisions - for instance, why do you not want the Fruit classes to know about Pesticide? I'm sure there is a good reason for this - but expressing that reason will help clarify in your mind exactly what your aims are - and ...
3,049,445
3,049,468
_dl_runtime_resolve -- When do the shared objects get loaded in to memory?
We have a message processing system with high performance demands. Recently we have noticed that the first message takes many times longer then subsequent messages. A bunch of transformation and message augmentation happens as this goes through our system, much of it done by way of external lib. I just profiled thi...
From the ld.so(8) man page, ENVIRONMENT section: LD_BIND_NOW (libc5; glibc since 2.1.1) If set to a non-empty string, causes the dynamic linker to resolve all symbols at program startup instead of deferring function call resolution to the point when they are first refere...
3,049,597
3,049,633
STL ostream_iterator writes to screen even though I overwrote it?
In my code, I have the following: ostream_iterator<double> doubleWriter(cout, " ~ "); // ... *doubleWriter = 1.1; doubleWriter++; *doubleWriter = 2.2; *doubleWriter = 3.3; // shouldn't 2.2 be overwritten? doubleWriter++; *doubleWriter = 44.2; cout << endl << endl; I expected it to output this: 1.1 ~ 3.3 ~ 44.2 ~ In...
For standard ostream_iterator, operator ++ (both prefix and postfix) is a no-op. It does nothing and makes no difference. There's no need to do the ++ manually, since the iterator always "advances" when you output something through it. P.S. According to library Defect Report 485, the intent was to require that assignm...
3,049,736
3,610,312
Compiling a DLL which includes Ogre3D gives an assertion error when used
I have a framework that I am building and is being compiled into a static library to be used by other projects. The library works perfectly without issues. The problem is that the link time is very long for the projects that use the library so I thought I will make a DLL project of the same framework. I started with ba...
Finally found the solution HERE Short explanation is that the DLL I was creating should be a non-MFC DLL without a DLL main, but Visual Studio gives me an MFC DLL template.
3,049,806
3,049,820
C++ destructor problem with boost::scoped_ptr
I have a question about the following code: #include <iostream> #include <boost/scoped_ptr.hpp> class Interface { }; class A : public Interface { public: A() { std::cout << "A()" << std::endl; } virtual ~A() { std::cout << "~A()" << std::endl; } }; Interface* get_a() { A* a = new A; retu...
You must define a virtual destructor in the base class, otherwise you'll get no polymorphic behavior. And more importantly, you get undefined behavior otherwise; §5.3.5/3: If the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the s...
3,049,824
3,049,841
C++: Return NULL instead of struct
I have a struct Foo. In pseudocode: def FindFoo: foo = results of search foundFoo = true if a valid foo has been found return foo if foundFoo else someErrorCode How can I accomplish this in C++? Edited to remove numerous inaccuracies.
C++ objects can never be null or empty. Pointers can hold a null pointer value indicating they point at nothing. The typical solution would be to throw an exception. Otherwise, use a pointer; just make sure you aren't returning the address of a temporary. I wouldn't recommend trying to teach yourself C++ with knowledge...
3,049,866
3,049,871
C++: Trouble with tr1::bind (C2065)
I'm getting a compiler error with bind: using namespace std; bool odp(int arg1, int arg2); // ... find_if(vec.begin(), vec.end(), tr1::bind(odp, iValue, _1)); // C2065 My goal is to curry odp(), so its first argument is iValue, and apply that function in find_if. The error: C2065: '_1' : undeclared identifier. Wha...
You need using namespace std::tr1::placeholders or using std::tr1::placeholders::_1.
3,049,936
3,049,957
Trying to instantiate a class member in C++ with a variable name
I am writing a program for class that is asking us to create a class of "book". We are then supposed to create new instantiations of that class upon demand from the user. I am new to C++ so I am attempting to code this out but am running into a problem. The main problem is how do I instantiate a class with a variab...
Given your type book, if you want to create a list of books, try using a container like std::vector, std::list or std::deque. typedef std::vector<book> library_type; library_type library; book catch22("Catch 22") library.push_back(catch22); book haltingState("Halting State"); library.push_back(haltingState); You ca...
3,049,952
3,049,976
Getting functions of inherited functions to be called
Let's say I have a base class Animal from which a class Cow inherits, and a Barn class containing an Animal vector, and let's say the Animal class has a virtual function scream(), which Cow overrides. With the following code: Animal.h #ifndef _ANIMAL_H #define _ANIMAL_H #include <iostream> using namespace std; class A...
A slight modification that stores pointers to animals should help: #ifndef _BARN_H #define _BARN_H #include "Animal.h" #include <vector> class Barn { std::vector<Animal *> animals; public: Barn() {} void insertAnimal(Animal *animal) {animals.push_back(animal);} void tortureAnimals() { for(int...
3,050,129
3,050,138
Will the compiler optimize escaping an inner loop?
The code I have looks like this (all uses of done shown): bool done = false; for(int i = 0; i < big; i++) { ... for(int j = 0; j < wow; j++) { ... if(foo(i,j)) { done = true; break; } ... } if(done) break; ... } will any compilers convert it to this: for(int i = 0; i < big...
Obviously this depends on the compiler. The best thing to do when you're unsure is to view the compiler's assembly output (all popular compilers have a switch for this). Even if you aren't familiar with assembly, you can at least compare the debug version with the optimized version. That being said, this is one of the ...
3,050,400
3,050,404
How do I create a duplicate instance of object contained in a shared pointer in c++?
I have an object which has both a copy constructor and assignment operator defined. It is enclosed inside a shared pointer. I want to make another shared pointer that contains a copy of the original shared pointer (i.e. new shared pointer to a new memory location, which however, has the same data as the original objec...
You invoke the copy constructor when creating the new object: std::shared_ptr<C> ptr1(new C()); // invokes the default constructor std::shared_ptr<C> ptr2(new C(*ptr1)); // invokes the copy constructor In this case, it's really no different than if you have regular, dumb pointers.
3,050,409
3,050,833
error LNK2001: unresolved external symbol
I am receiving this error >GXRenderManager.obj : error LNK2001: unresolved external symbol "private: static class GXRenderer * GXRenderManager::renderDevice" (?renderDevice@GXRenderManager@@0PAVGXRenderer@@A) The following is my code... GXDX.h class GXDX: public GXRenderer { public: void Render(); void StartU...
You need an actual definition (or instance) for the static member GXRenderer::renderDevice. The class declares it, but there needs to be a definition of it in exactly one place. In your GXRenderManager.cpp file have a line like so: GXRenderer * GXRenderer::renderDevice = NULL; or whatever initialization might be appr...
3,050,621
3,050,764
File writing with overlapped IO vs file writing in a separate thread
Is there any advantage in using file writing with overlapped IO in Windows, vs just doing the file writing in a separate thread that I create? [Edit - please note that I'm doing the file writes without system caching, ie I use the FILE_FLAG_NO_BUFFERING flag in CreateFile)
Since all writes are cached in the system cache by default, there is little advantage to doing overlapped I/O or creating a separate thread for writes at all. Most WriteFile calls are just memcpys at their core, which are lazily written to disk by the OS in an optimal fashion with other writes. You can, of course, turn...