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 |
|---|---|---|---|---|
665,688 | 665,703 | Is stereoscopy (3D stereo) making a come back? | I'm working on a stereoscopy application in C++ and OpenGL (for medical image visualization). From what I understand, the technology was quite big news about 10 years ago but it seems to have died down since. Now, many companies seem to be investing in the technology... Including nVidia it would seem.
Stereoscopy is al... | With nVidia's 3D kit you don't need to "make a stereoscopy application", drivers and video card take care of that. 10 years ago there was good quality stereoscopy with polarized glasses and extremely expensive monitors and low quality stereoscopy with red/cyan glasses. What you have now is both cheap and good quality. ... |
665,741 | 665,783 | C++/Qt: drawing a caret | I'm learning Qt. I just started to write a text editor from scratch by inheriting QAbstractScrollArea. I'm doing this just for practice. But now I'm faced with the problem of displaying a caret. What comes to my mind is painter.drawLine and QTimer. Can you give some advices on this. I would also be glad hear some strat... | Take at a look at paintEvent() in QLineEdit. It has a timer that toggles the cursor on and off. The real cursor drawing is done via QTextLayout::drawCursor.
For a text editor in general, have a look at QPlainTextEdit and QTextEdit.
|
665,781 | 665,789 | Copy Constructor in C++ is called when object is returned from a function? | I understand copy constructor is called on three instances
When instantiating one object and initializing it with values from another object.
When passing an object by value.
3. When an object is returned from a function by value.
I have question with no.3
if copy constructor is called when an object value is return... | It's called exactly to avoid problems. A new object serving as result is initialized from the locally-defined object, then the locally defined object is destroyed.
In case of deep-copy user-defined constructor it's all the same. First storage is allocated for the object that will serve as result, then the copy construc... |
665,825 | 665,854 | Copy constructor vs. return value optimization | In a previous question, it appeared that a plain return-by-value function always copies its return argument into the variable being assigned from it.
Is this required by the standard, or can the function be optimized by constructing the 'assigned to' variable even within the function body?
struct C { int i; double d; }... | The standard allows any level of copy omission here:
construct a local temporary, copy-construct it into a return value, and copy-construct the return value into the local "c". OR
construct a local temporary, and copy-construct that into "c". OR
construct "c" with the arguments "i,d"
|
666,078 | 666,135 | What component do I need to monitor my internet traffic on my PC? | I would like to be able to see and monitor my internet data (http/emule/email) on my own PC using Windows XP. I am thinking of something like WireShark but I would like to control it programmatically.
I would be using C or C++.
How can I do this?
| WireShark uses winpcap to do it's thing.
Winpcap comes with a C interface.
|
666,280 | 666,294 | Problem with dereference operator and functions | I have a function A(), that returns a pointer to an object. In function B() I try to change a member of that object in the following way:
void B()
{
ObjType o = *getObj();
o.set("abc");
}
Object o is stored in an array, and when I print the value of the member, it seems nothing happened, and the member still h... | The following line is most likely copying the object:
ObjType o = *getObj();
That's why nothing happens. If you don't want to use a pointer as shown in your second snippet, you can use a reference like this:
ObjType& o = *getObj();
o.set("abc");
|
666,320 | 666,352 | Accessing public class memory from C++ using C | Greetings Everyone.
I'm currently writing a multi-language programe in C, C++ and fortran on UNIX, unfortunatly I run into "Segmentation Error" when I try and execute after compiling.
I've narrowed down the problem to the interface between the C++ and C sections of my program. The first section consists of main.ccp an... | Provided you stay within the bounds of the vector, what you are doing would seem to be OK.
You can treat a std::vector exactly as if it were a C array by doing what you are doing - taking the address of the first element. The C++ Standard has been changed to specifically allow this kind of usage.
Can't find a copy of C... |
666,601 | 666,788 | What is the correct way of reading from a TCP socket in C/C++? | Here's my code:
// Not all headers are relevant to the code snippet.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
char *buffer;
stringstream readStream;
bool readData = true;
while (readData)
{
... | Without knowing your full application it is hard to say what the best way to approach the problem is, but a common technique is to use a header which starts with a fixed length field, which denotes the length of the rest of your message.
Assume that your header consist only of a 4 byte integer which denotes the length ... |
666,628 | 666,706 | Importing explicitly instantiated template class from dll | Being a dll newbie I have to ask the allmighty SO about something.
Say I explicitly instantiate a template class like this:
template class __declspec(dllexport) B<int>;
How do I use import this templated class again?
I've tried the adding the code below in my .cpp file where I want to use B
template class __declspec(... | When you instantiate a template fully -- you have a complete type. It is no different from any other types. You need to include the header for B and also compile-time linking in with a lib file or dynamically load the dll to link to the definition.
Have you read this article: http://support.microsoft.com/kb/168958 ?
He... |
666,672 | 672,532 | Forcing my MFC app to run as Administrator on Vista | I have an MFC app built using Visual Studio 2008 and it needs to run on W2K, XP, 2003 and Vista. The application writes to HKLM in the registry and will only work on Vista if you run it as Administrator.
My question is: can I force the app to run as Adminstrator automatically? Does it involve creating a manifest file... | I found out how to do this using some advanced C++ linker options:
Open the project's Property Pages dialog box.
Expand the Configuration Properties node.
Expand the Linker node.
Select the Manifest File property page.
Modify the Enable User Account Control (UAC), UAC Execution Level, and UAC Bypass UI Protection prop... |
666,713 | 666,846 | Output conflicts between C & C++ | Greetings Everyone
I am currently trying to write a multi-language program (C, C++ and fortran) though am achieving segmentation errors. I've ruled out vectors and the like in: Accessing public class memory from C++ using C
I've narrowed now the cause to the use of 'cout' experssions in my C++ segments and printf(...) ... | You need to check that the files are opened correctly - i.e. the the pointer returned by fopen() is not NULL. Also,
int ReturnY ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
return elemX;
}
I take it return elemx should be return elemy?... |
667,015 | 667,026 | #include <lib.h> gives symbol not found, why? | I have this code:
#include <iostream>
#include <mp4.h>
int main (int argc, char * const argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
MP4Read("filename", MP4_DETAILS_ALL );
return 0;
}
And i've added -I/opt/local/include and -L/opt/local/lib to the path (where the mp4 library resi... | You need to link the library most likely, i.e. add -lmp4 or similar to your linking commands.
|
667,055 | 673,102 | fread error with DJGPP | While reading a binary file using DJGPP on DOS this code hangs.
This happens when the fread call is made. If the call is removed then the program runs successfully.
The same code runs fine through Visual C++ 2008.
Has anyone experienced similar issues with djgpp ?
Am I missing out on something really simple ?
char... |
I don't see what 'fp' is. I just have to assume it's 'FILE * fp;'.
I don't see that you actually include < stdio.h >, and have to assume you do.
I don't see that you actually include < iostream > and declare 'using namespace std;', and have to assume you do.
I don't see what comes after the fread() call that could tel... |
667,183 | 667,206 | Padding stl strings in C++ | I'm using std::string and need to left pad them to a given width. What is the recommended way to do this in C++?
Sample input:
123
pad to 10 characters.
Sample output:
123
(7 spaces in front of 123)
| std::setw (setwidth) manipulator
std::cout << std::setw (10) << 77 << std::endl;
or
std::cout << std::setw (10) << "hi!" << std::endl;
outputs padded 77 and "hi!".
if you need result as string use instance of std::stringstream instead std::cout object.
ps: responsible header file <iomanip>
|
667,396 | 667,415 | Parameter passed by const reference returned by const reference | I was reading C++ Faq Second Edition , faq number 32.08 .
FAQ says that parameter passed by const reference and returned by const reference can cause dangling reference.
But it is ok if parameter is passed by reference and returned by reference.
I got it that it is unsafe in case of const reference but how is it safe ... | if you have like
const Foo & bar(const Foo &f) { return f; }
and call it like
const Foo &ret = bar(Foo());
This compiles, but the problem is that now 'ret' is a dangling reference, because the temporary object created by the call to Foo() gets freed after bar returns. The detailed execution sequence here is:
tempora... |
667,634 | 667,680 | What is the performance cost of having a virtual method in a C++ class? | Having at least one virtual method in a C++ class (or any of its parent classes) means that the class will have a virtual table, and every instance will have a virtual pointer.
So the memory cost is quite clear. The most important is the memory cost on the instances (especially if the instances are small, for example ... | I ran some timings on a 3ghz in-order PowerPC processor. On that architecture, a virtual function call costs 7 nanoseconds longer than a direct (non-virtual) function call.
So, not really worth worrying about the cost unless the function is something like a trivial Get()/Set() accessor, in which anything other than inl... |
667,912 | 667,952 | Boost (BGL): How do dis-obfuscate my errors? | I seem to recall reading about a way to 'reduce' the size of template spew in compiler errors associated with the boost libraries. My recollection is that it gives the template parameters nicer names than the compiler default naming (which is quite horrid).
Is this real, or did I dream about it? I've been trying to fin... | I have heard this works well.
http://www.bdsoft.com/tools/stlfilt.html
It is a perl script that parses the error messages a generates more readable versions
|
668,103 | 668,248 | How to tell compiler to NOT optimize certain code away? | Is there a way to tell the compiler (g++ in my case) to not optimize certain code away, even if that code is not reachable? I just want those symbols in the object file.
Example: Here is a simple function, and I do want this function to be compiled, even if it's never called.
void foo(){
Foo<int> v;
}
If there is no... | You are running into the One Definition Rule. In one file you have a definition:
template<class T>
struct Foo {
T val_;
Foo(T val) : val_(val) {
// heavy code, long compile times
}
};
and in another a different definition:
template<class T>
struct Foo {
T val_;
Foo(T val); // no heavy code, can include... |
668,325 | 846,883 | SwapBuffers crashing my program! | I have an OpenGL program that works on all of my computers but one. It's a desktop with Vista 64 and a Radeon HD4850. The problem seems to be in my call to SwapBuffers(hdc).
It compiles fine and then gives me an exception:
Unhandled exception at 0x00000000 in Program.exe: 0xC0000005: Acces violation.
Using VC++ to brea... | This is almost definitely a bug in the drivers. The reason why you can't see the value of hdc is because the top stackframe for the crash is actually inside ATKOGL32.dll but since there are no symbols for that the debugger shows you your code. As far as I can tell ATKOGL32.dll is actually an ASUS wrapper for the ATI dr... |
668,604 | 678,949 | Adding Qt to Xcode project? | I have a fairly complex Xcode project and I want to add Qt to it. I know that I can create a new project using qmake -spec macx-xcode project.pro but I don't want to have to hand configure my old project over the auto generated Qt project. Is there another option?
[edited in a more general question below]
It seems like... | One of the main points of using Qt is the portability of the Gui. It only makes sense to extend this feature to your build process by using qmake and allowing users/developers generate whichever build system they want to use (make, visualstudio, xcode).
No, qmake is not well documented and more poignantly there are no... |
668,653 | 668,711 | How could I implement logical implication with bitwise or other efficient code in C? | I want to implement a logical operation that works as efficient as possible. I need this truth table:
p q p → q
T T T
T F F
F T T
F F T
This, according to wikipedia is called "logical implication"
I've been long trying to figure out how to make this with bitwise operations in C wi... | FYI, with gcc-4.3.3:
int foo(int a, int b) { return !a || b; }
int bar(int a, int b) { return ~a | b; }
Gives (from objdump -d):
0000000000000000 <foo>:
0: 85 ff test %edi,%edi
2: 0f 94 c2 sete %dl
5: 85 f6 test %esi,%esi
7: 0f 95 c0 ... |
669,105 | 669,224 | C++ "this" doesn't match object method was called on | I have come across what seems like a really annoying bug running my C++ program under Microsoft Visual C++ 2003, but it could just be something I'm doing wrong so thought I'd throw it out here and see if anybody has any ideas.
I have a hierarchy of classes like this (exactly as is - e.g. there is no multiple inheritanc... | I believe you are simply seeing an artifact of the way that the compiler is building the vtables. I suspect that CMotion has virtual functions of it's own, and thus you end up with offsets within the derived object to get to the base object. Thus, different pointers.
If it's working (i.e. if this isn't producing crash... |
669,347 | 669,351 | COM method call returns Catastrophic Failure | Note:
Pass BSTR variable to COM method, HRESULT return is 8000FFFF
Previous calls with interface pointer, was successful: HRESULT is 0
Execution, inside Visual Studio succeeds, outside fails - release and debug
Illustration:
const char *simFile;
simFile = new char;
//omitted
_bstr_t simFileToOpen(simFile);
BSTR raw_s... | simFile looks to be a single character stored inside a const char*.
It is not a NULL terminated string, unless it is an empty string and it's contents are 0.
Are you sure you didn't mean to do something like:
const char *simFile = new char[1024];
strcpy(simFile, "path");
Even better yet you can just use SysAllocString... |
669,598 | 669,614 | problem with socket programming in c\c++ | #include "stdafx.h"
#include <windows.h>
#include <winsock.h>
#include <stdio.h>
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR IpCmdLine,int nCmdShow)
{
WSADATA ws;
char buf[100];
WSAStartup(0x0101,&ws);
sprintf(buf,"%d.%d",HIBYTE(ws.wVersion),LOBYTE(ws.wVersion));
Messag... |
stdafx is used to implement precompiled headers in VC++. You can put your library headers like windows.h and winsock.h, etc.. in there and they will only be compiled once each time you modify stdafx.h.
APIENTRY is usually just a define for __stdcall, but sometimes it is defined blank (if __stdcall is not supported fo... |
669,742 | 669,774 | Accessing class members on a NULL pointer | I was experimenting with C++ and found the below code as very strange.
class Foo{
public:
virtual void say_virtual_hi(){
std::cout << "Virtual Hi";
}
void say_hi()
{
std::cout << "Hi";
}
};
int main(int argc, char** argv)
{
Foo* foo = 0;
foo->say_hi(); // works well
fo... | The object foo is a local variable with type Foo*. That variable likely gets allocated on the stack for the main function, just like any other local variable. But the value stored in foo is a null pointer. It doesn't point anywhere. There is no instance of type Foo represented anywhere.
To call a virtual function, the ... |
669,989 | 670,005 | How to implement process-global variable in C++? | Normally using a variable in a .cpp file results in the variable being globally available, like this:
.h file:
extern int myGlobal;
void work();
.cpp file:
int myGlobal = 42;
void work(){ myGlobal++; }
When the .cpp file is put in a static library and more than one shared library (DLL) or executable links against the... | Simple: make all the DLLs in the process link to a single DLL that exposes the variable.
|
670,026 | 670,042 | Best way to avoid a thousand if statements? | I basically have this problem: right now, we have a system where it gets a string as input, and it basically says ACTION:.
For each of the actions there is an automatically generated function(Rational Rose GRRR), such as
bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
bouncer_comm.askforname().sen... | I like @cobbal's idea of the function pointer hash above, but you could replace this conditional logic with polymorphism.
see: http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism
|
670,041 | 670,050 | Templated assignment operator: valid C++? | Just a quick and simple question, but couldn't find it in any documentation.
template <class T>
T* Some_Class<T>::Some_Static_Variable = NULL;
It compiles with g++, but I am not sure if this is valid usage. Is it?
| Yes this code is correct. See this C++ Templates tutorial for more information
http://www.is.pku.edu.cn/~qzy/cpp/vc-stl/templates.htm#T14
|
670,101 | 670,143 | C++ functions: ampersand vs asterisk | Let's say you have a function that modifies a variable.
Should you write it like this: void myfunc(int *a) or like this void myfunc(int &a)?
The former forces you to call the function with myfunc(&b) so the caller is aware that b will be modified, but the latter is shorter and can be called simply with myfunc(b). So wh... | Pointers (ie. the '*') should be used where the passing "NULL" is meaningful.
For example, you might use a NULL to represent that a particular object needs to be created, or that a particular action doesn't need to be taken.
Or if it ever needs to be called from non-C++ code. (eg. for use in shared libraries)
eg. The l... |
670,154 | 670,163 | Why was the ampersand chosen as the symbol for references in C++? | Does anyone have an idea why the ampersand was chosen as the way to denote references in C++?
AFAIK (though I don't have the book near me), Stroustroup didn't explain that choice, which I find a little odd because the same symbol was already used for address-of in C.
| Stroustrup was always very reluctant to introduce a new reserved symbol or name, so he probably used it to avoid making the feature look weird to users of C.
|
670,308 | 670,322 | Alternative to vector<bool> | As (hopefully) we all know, vector<bool> is totally broken and can't be treated as a C array. What is the best way to get this functionality?
So far, the ideas I have thought of are:
Use a vector<char> instead, or
Use a wrapper class and have vector<bool_wrapper>
How do you guys handle this problem? I need the c_arra... | Use std::deque if you don't need the array, yes.
Otherwise use an alternative vector that doesn't specialize on bool, such as the one in Boost Container.
|
670,465 | 670,508 | Using boost::iostreams::tee_device? | Can someone help me?
I am trying to do something like the following:
#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>
#include <sstream>
#include <cassert>
namespace io = boost::iostreams;
typedef io::stream<io::tee_device<std::stringstream, std::stringstream> > Tee;
std::stringstream ss1, ... | You use the constructor-forwarding version of io::stream, which construct a tee-stream itself and forward all arguments to that. C++03 has only limited capabilities when it comes to forwarding arguments to functions (amount of overloads needed easily grow exponentially). It (io::stream) makes the following restrictions... |
670,541 | 670,564 | g++ header included: still doesn't find definition | Good evening :)
I'm playing around with g++ and makefiles. I've gotten to this point:
foo.h:
#ifndef _FOO_H_
#define _FOO_H_
#include "bar.h"
class foo {
private:
bar something;
public:
bool start();
bool stop();
};
#endif // _FOO_H_
Foo.h is eventually included in my main cpp file so I can set things i... |
Was messing around with boost::asio and kind of forgot I still left this on top of my headers somewhere: using boost::asio::ip::tcp;
Let's just say there's a boost::asio::ip::tcp::bar function
Dan Saks explains some reasons why you should typedef your class names, even though it might seem redundant.
Well, you've ru... |
670,734 | 670,744 | Pointer to class data member "::*" | I came across this strange code snippet which compiles fine:
class Car
{
public:
int speed;
};
int main()
{
int Car::*pSpeed = &Car::speed;
return 0;
}
Why does C++ have this pointer to a non-static data member of a class? What is the use of this strange pointer in real code?
| It's a "pointer to member" - the following code illustrates its use:
#include <iostream>
using namespace std;
class Car
{
public:
int speed;
};
int main()
{
int Car::*pSpeed = &Car::speed;
Car c1;
c1.speed = 1; // direct access
cout << "speed is " << c1.speed << endl;
c1.*pSpeed = 2... |
670,958 | 671,007 | Accessors vs. public members | I have a class with a lot of built-in type members with read/write access. Should I make them public members and provide get/set methods for each one? How about structures?
| If there are invariants you need to preserve, then yes. Otherwise, don't bother.
|
671,423 | 671,427 | C++ STL Vectors: Get iterator from index? | So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like vector.insert(pos, first, last) is the function I want... except I only have first and last as ints. Is there any nice way I can get an iterator to these values?
| Try this:
vector<Type>::iterator nth = v.begin() + index;
|
671,461 | 671,465 | How can I execute external commands in C++/Linux? | I just want to know which is the best way to execute an external command in C++ and how can I grab the output if there is any?
Edit: I Guess I had to tell that I'm a newbie here in this world, so I think I'm gonna need a working example. For example I want to execute a command like:
ls -la
how do I do that?
| Use the popen function.
Example (not complete, production quality code, no error handling):
FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);
|
671,657 | 671,682 | Windows Mobile Command Line Compiler | What is the name of the Command Line Compiler for a C/C++ program that target's Windows Mobile?
I have Visual Studio 2008 Professional installed and I need to be able to compile a program from the command line. I've checked the project properties in Visual Studio and it shows me all of the parameters that are being ... | The name of the command line C++ compiler is cl.exe
The executable for windows ce is usually located at
%ProgramFiles%\Microsoft Visual Studio 9.0\VC\ce\bin\x86_arm\cl.exe
x86_arm can be replaced with x86_mips or x86_sh depending on the particular architecture.
Here's some further information on the Windows CE / M... |
671,659 | 672,041 | How to deallocate memory when a Qt window closes? | I am currently creating a program in Qt, OpenCv, Mac os X. I have a main window, and then a separate window that is opened. I pass the new window several matrix clones in the constructor:
ImageWindow *imageWin = new ImageWindow(
cvCloneMat(getData->getMasterRawMat(1)),
cvCloneMat(getData->getMasterRawMat(2)), ... | You can do that in e.g. your closeEvent(). Alternatively, if you use Qt::WA_DeleteOnClose for your widget attributes, the widget will be deleted when it is closed, which means you can place some clean-up routines in the destructor.
|
671,703 | 671,709 | Array index out of bound behavior | Why does C/C++ differentiates in case of array index out of bound
#include <stdio.h>
int main()
{
int a[10];
a[3]=4;
a[11]=3;//does not give segmentation fault
a[25]=4;//does not give segmentation fault
a[20000]=3; //gives segmentation fault
return 0;
}
I understand that it's trying to access m... | The problem is that C/C++ doesn't actually do any boundary checking with regards to arrays. It depends on the OS to ensure that you are accessing valid memory.
In this particular case, you are declaring a stack based array. Depending upon the particular implementation, accessing outside the bounds of the array will... |
671,760 | 671,805 | Relational Operator Implementation Dilemma | I'm in the process of designing several classes that need to support operators !=, >, <=, and >=. These operators will be implemented in terms of operators == and <.
At this stage, I need to make a choice between inheritance¹ and forcing my consumers to use std::rel_ops² "manually".
[1] Inheritance (possible implementa... | Have you considered using boost, and having your class inherit from boost::less_than_comparable<T> and boost::equality_comparable<T>? It is akin to your first suggestion, with some pros and cons. Pros: avoids code duplication; Cons: creates a dependency on boost.
Since boost is a very common C++ library (if you don't u... |
671,837 | 671,874 | Is there a best practice for accessing C++ native COM functions to interop from C#? | Is there a best practice for accessing C++ native COM functions to interop from C#?
For example, if I have 100 C++ methods (basically a native library) that interacts with a core window component.
I want to basically make a wrapper for these C++ methods in C#, so all my newly hired employees can use that instead of C++... | If your C++ methods are in a COM object, then you can use COM interop from C#. See CLR Inside Out: Introduction to COM Interop for a good introduction.
If those C++ methods are more like traditional API calls, then you'll want to use Platform Invoke (i.e. PInvoke). That entails creating managed prototypes in C# for t... |
671,925 | 671,931 | What exactly are C++ definitions, declarations and assignments? | I tend to use the words define, declare and assign interchangeably but this seems to cause offense to some people. Is this justified? Should I only use the word declare for the first time I assign to a variable? Or is there more to it than that?
| Define and declare are similar but assign is very different.
Here I am declaring (or defining) a variable:
int x;
Here I am assigning a value to that variable:
x = 0;
Here I am doing both in one statement:
int x = 0;
Note
Not all languages support declaration and assignment in one statement:
T-SQL
declare x int;
se... |
672,352 | 672,394 | How is dynamic memory managed in std::vector? | How does std::vector implement the management of the changing number of elements: Does it use realloc() function, or does it use a linked list?
Thanks.
| It uses the allocator that was given to it as the second template parameter. Like this then. Say it is in push_back, let t be the object to be pushed:
...
if(_size == _capacity) { // size is never greater than capacity
// reallocate
T * _begin1 = alloc.allocate(_capacity * 2, 0);
size_type _capacity1 = _cap... |
672,373 | 672,376 | Can I call a base class's virtual function if I'm overriding it? | Say I have classes Foo and Bar set up like this:
class Foo
{
public:
int x;
virtual void printStuff()
{
std::cout << x << std::endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
// I would like to call Foo.printStuff() here...
std::cout << y << ... | In C++ you have to explicitly name the base class in calling the derived class method. This can be done from any method from the derived class. The override is a special case of the method of the same name. In Java there is no multi inheritance, so you can use super which will uniquely name the base class. The C++ synt... |
672,392 | 848,234 | How can you use utility functions with UnitTest++ | I'm using UnitTest++ for unit testing C++ code.
In my tests, there's a group of tests I repeat several times. What I'd like is for a utility function to perform these tests. In short, I'd like to take this:
TEST( foo ) {
Foo one;
Foo two;
// init one & two
// lots of CHECK_CLOSE(one.bar, two.bar, 1e-5)... | Write a macro to do it. Don't let the "macros are evil" mantra hide this fact from you: Macros are designed to generate repetitive code.
|
672,421 | 672,460 | boost lambda collection size evaluation | I have a function of the form:
void DoSomething(const boost::function<bool ()>& condition, other stuff);
This function does some work and returns only when the condition is true. The condition has been expressed as a functor argument because I want to supply different conditions at different call sites.
Now, this is ... | The problem is, that the lambda function stores a copy of the data vector, not a reference. So size() is called on the copy, not the original object that you are modifying. This can be solved by wrapping data with boost::ref, which stores a reference instead:
boost::function<size_t ()> size = boost::bind(&std::vector<s... |
672,461 | 672,482 | what is "stack alignment"? | What is stack alignment?
Why is it used?
Can it be controlled by compiler settings?
The details of this question are taken from a problem faced when trying to use ffmpeg libraries with msvc, however what I'm really interested in is an explanation of what is "stack alignment".
The Details:
When runnig my msvc complie... | Alignment of variables in memory (a short history).
In the past computers had an 8 bits databus. This means, that each clock cycle 8 bits of information could be processed. Which was fine then.
Then came 16 bit computers. Due to downward compatibility and other issues, the 8 bit byte was kept and the 16 bit word was in... |
672,618 | 672,631 | Macro expansion in C++ | How can I define a macro (or a workaround for this) where the parameter is at the beginning of the line?
#define SINGLETON_IMPLEMENTATION(className) \
##className* ##className::instance_ = NULL;
This give a compiler warning (GCC 3.2.3): " '##' cannot appear at either end of a macro expansion"
| ## is the concatenation operator; the compiler is just complaining about that.
You cannot concatenate a token without something before it, i.e. at the beginning of the macro expansion; just try to remove the ## at the beginning of the second line.
Also the second ## seems wrong. If you just want to initialize a singlet... |
672,700 | 672,738 | What is the use of passing const references to primitive types? | In a project I maintain, I see a lot of code like this for simple get/set methods
const int & MyClass::getFoo() { return m_foo; }
void MyClass::setFoo(const int & foo) { m_foo = foo; }
What is the point in doing that instead of the following?
int MyClass::getFoo() { return m_foo; } // Removed 'const' and '&'
void ... | The difference is that if you get that result into a reference yourself you can track the changes of the integer member variable in your own variable name without recalling the function.
const &int x = myObject.getFoo();
cout<<x<<endl;
//...
cout<<x<<endl;//x might have changed
It's probably not the best design choic... |
672,729 | 672,774 | How to convert c++ std::list element to multimap iterator | I have
std::list<multimap<std::string,std::string>::iterator> >
Now i have new element:
multimap<std::string,std::string>::value_type aNewMmapValue("foo1","test")
I want to avoid the need to set temp multimap and do insert to the new element just to get its iterator back
so i could to push it back to the:
std::list... | You need to insert the key-value pair into a multimap before getting an iterator for it.
An iterator does not work by itself. If you are storing iterators from several different multimaps you probably need to store more than just an iterator in the list.
Perhaps:
a pair<multimap<std::string,std::string>::iterator, mul... |
672,796 | 672,832 | ListView with LVS_OWNERDATA flag | I want to make a CListView that will read his rows from e remote server using socket. The rows may be more than a million that's why i need to read rows only when I need them and may be read them in a groups (with more that 1 row per request). I also need to support sorting by rows.
May be I have to use List Control wi... | Read Raymond Chen about OWNERDATA listviews. You'll need to implement your own cache for fetched data, and display something sensible while data is being fetched. I don't think Next/Prev buttons are a good idea, the list view handles its own navigation (scrollbar, keyboard shortcuts etc.)
|
672,843 | 672,886 | Can templates be used to access struct variables by name? | Let's suppose I have a struct like this:
struct my_struct
{
int a;
int b;
}
I have a function which should set a new value for either "a" or "b". This function also requires to specify which variable to set. A typical example would be like this:
void f(int which, my_struct* s, int new_value)
{
if(which == 0)
... | #include <iostream>
#include <ostream>
#include <string>
struct my_struct
{
int a;
std::string b;
};
template <typename TObject, typename TMember, typename TValue>
void set( TObject* object, TMember member, TValue value )
{
( *object ).*member = value;
}
class undo_token {};
template <class TValue>
clas... |
672,899 | 695,237 | C++: How to open IShellFolder drive folder from a shortcut | I am using the following command in a shortcut to open my virtual drive in Windows Explorer.
%SystemRoot%\Explorer.exe /e,::{MyExtension CLSID}
The virtual drive uses IShellFolder interface and is a ShellExtension. It has a couple of predefined folders in it.
The problem is that I can open the virtual drive in Windows ... | I took the GMail Drive Shell extension, installed it, and create a folder inside the namespace. Then I use the above method (/E,::{CLSID}) to create the shortcut and added ",foldername" at the end.
It worked perfectly, I think that you need to check your IPersistFolder::Initialize implementation.
|
673,114 | 673,118 | Is it possible to create method call dispatcher in C++? | Consider a following code:
struct X {
void MethodX() {
...
}
};
struct Y {
void MethodY() {
...
}
};
void test () {
X x;
Y y;
Dispatcher d;
d.Register("x", x, &X::MethodX);
d.Register("y", y, &Y::MethodY);
d.Call("x");
d.Call("y");
}
The question is how to implement Dispatcher.
I don't ... | Take a look at boost::function, it does this.
|
673,240 | 673,389 | how do I print an unsigned char as hex in c++ using ostream? | I want to work with unsigned 8-bit variables in C++. Either unsigned char or uint8_t do the trick as far as the arithmetic is concerned (which is expected, since AFAIK uint8_t is just an alias for unsigned char, or so the debugger presents it.
The problem is that if I print out the variables using ostream in C++ it tr... | I would suggest using the following technique:
struct HexCharStruct
{
unsigned char c;
HexCharStruct(unsigned char _c) : c(_c) { }
};
inline std::ostream& operator<<(std::ostream& o, const HexCharStruct& hs)
{
return (o << std::hex << (int)hs.c);
}
inline HexCharStruct hex(unsigned char _c)
{
return HexCharSt... |
673,491 | 673,994 | How to code inlineable mutual abstracion in C++? | Example first:
template <class HashingSolution>
struct State : public HashingSolution {
void Update(int idx, int val) {
UpdateHash(idx, val);
}
int GetState(int idx) {
return ...;
}
};
struct DummyHashingSolution {
void UpdateHash(int idx, int val) {}
void RecalcHash() {}
};
struct MyHashingSol... | As jalf suggests in the comments, you probably want to use a variant of the Curiously Recurring Template Pattern (CRTP). That is, make MyHashingSolution a class template parametrised by the derived class:
template <typename D>
struct MyHashingSolution {
typedef D Derived;
void UpdateHash(int idx, int val) {
... |
673,554 | 673,606 | How can I refactor C++ source code using emacs? | I'm interested mostly in C++ and method/class name/signature automatic changes.
| I do this a lot, so I'm axiously awaiting other replies too.
The only tricks I know are really basic. Here are my best friends in Emacs when refactoring code:
M-x query-replace
This allows you to do a global search and replace. You'll be doing this a ton when you move methods and commonly-accessed data to other classe... |
673,751 | 673,898 | Logic design pattern | In a game, many entities should be updated every frame. Im toying with different design patterns to achieve this. Up until now, Ive had a singleton manager class to which every Logic instance is added. But Im considering the following, a static list in the Logic class itself. This is nice since it would remove a class ... | First, you need to use remove() instead of erase() (the latter would need an iterator as argument)
If you use a slightly different loop like
std::list<Logic*>::iterator it = all.begin();
while (it != all.end()) {
Logic* current = *it;
++it;
current->update(deltatime);
}
you can even overcome the problem siukurni... |
673,930 | 673,963 | What is the workaround for unaligned memory access exception on ARM9 using C? | Architecture ARM9. Programming Language C.
We have a third-party stack and one of the calls takes a pointer(pBuffer) to a memory location. Within the stack, they are free to move around the pointer passed and access it as they wish. Unfortunately, they offset the passed in pointer and passed it into a another function ... | Copy the value byte by byte. Cast it to a (unsigned) char pointer, and then copy a byte at a time.
It's not pretty, but it doesn't sound like you have many options.
|
674,009 | 674,051 | How do I use an unmanaged class from a managed DLL in .NET? | I have an unmanaged class that I'm trying to dllexport from a managed DLL file. I'm trying to use the unmanaged class in another managed DLL file. However, when I try to do this I get link errors.
I've done this lots of times with unmanaged DLL files, so I know how that works. I know how to use "public ref", etc. in ma... | You need to use an interop assembly for unmanaged libraries or COM components. Here is a link with good information regarding this.
|
674,155 | 674,170 | Why this sample of .NET StructLayout for C++ | From http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute(VS.71).aspx:
[C++]
[StructLayout(LayoutKind::Explicit, Size=16, CharSet=CharSet::Ansi)]
__value class MySystemTime {
public:
[FieldOffset(0)] short int wYear;
[FieldOffset(2)] short int wMonth;
[FieldOffset(4)]... | The things in square brackets are called attributes, and appear often in C# code. They appear here to have the same meaning, as this is not strictly C++. It has Microsoft extensions to allow integration with the CLI.
When you declare such a struct in C or C++, this does not guarantee a particular memory layout. To cont... |
674,413 | 674,491 | Ignoring EOF on std::cin in C++ | I have an application that implements an interactive shell, similar to how the Python console / irb works. The problem now is that if the user accidentally hits ^D EOF is issued and my getline() call returns an empty string which i treat as "no input" and display the prompt again.
This then results in an endless loop ... | Correct solution thanks to litb:
if (!getline(std::cin, str)) {
std::cin.clear();
std::cout << std::endl;
}
|
674,456 | 674,541 | Where is Unicode version of atof in Windows Mobile | I have a C++ application where I'm replacing a number of sscanf functions with atoi, atof, etc... for performance reasons. The code is TCHAR based so it's _stscanf getting replaced with _ttoi and _ttof. Except there isn't a _ttof on Windows Mobile 5, or even a _wtof for explicit wide character support. I've ended up... | One of the problems of Windows Mobile is the size of RAM and ROM on the device. Therefore a lot of the redundant routines are removed to make sure the OS is as small as possible.
|
674,635 | 674,743 | Member pointer to array element | It's possible to define a pointer to a member and using this later on:
struct foo
{
int a;
int b[2];
};
int main()
{
foo bar;
int foo::* aptr=&foo::a;
bar.a=1;
std::cout << bar.*aptr << std::endl;
}
Now I need to have a pointer to a specific element of an array, so normally I'd write
int foo::* bptr=&(foo:... | The problem is that, accessing an item in an array is another level of indirection from accessing a plain int. If that array was a pointer instead you wouldn't expect to be able to access the int through a member pointer.
struct foo
{
int a;
int *b;
};
int main()
{
foo bar;
int foo::* aptr=&(*foo::b); // You... |
674,718 | 675,047 | How do I use DLLImport with structs as parameters in C#? | All the examples I can find using DLLImport to call C++ code from C# passes ints back and forth. I can get those examples working just fine. The method I need call takes two structs as its import parameters, and I'm not exactly clear how I can make this work.
Here's what I've got to work with:
I own the C++ code, so I ... | The MSDN topic Passing Structures has a good introduction to passing structures to unmanaged code. You'll also want to look at Marshaling Data with Platform Invoke, and Marshaling Arrays of Types.
|
674,930 | 674,949 | Go to the end of the C++ function in Vim | If I am in the middle of the function, I would like go to the very end of it in vim. I run into this problem as we sometimes have function of 500+ lines long (don't ask why).
I use vim, gvim.
| You can use the "]}" command. You may have to repeat it depending on how nested you are.
|
674,933 | 683,806 | Corner Stitching Datastructure, Any Open Source Implementations? | I recall learning about the corner-stitched data structure a number of years ago and have been fascinated with it ever since. It originated with a paper by Ousterhout.
I've searched and not been able to find a free/open implementations. I'd prefer a C++ implementation, but at this point would accept any pointers peop... | Ousterhout's own software package Magic implements corner stitching. The C source code is available BSD-licensed at http://opencircuitdesign.com/magic.
|
674,982 | 674,996 | Performance hit from C++ style casts? | I am new to C++ style casts and I am worried that using C++ style casts will ruin the performance of my application because I have a real-time-critical deadline in my interrupt-service-routine.
I heard that some casts will even throw exceptions!
I would like to use the C++ style casts because it would make my code more... | If the C++ style cast can be conceptualy replaced by a C-style cast there will be no overhead. If it can't, as in the case of dynamic_cast, for which there is no C equivalent, you have to pay the cost one way or another.
As an example, the following code:
int x;
float f = 123.456;
x = (int) f;
x = static_cast<int>(f);... |
675,005 | 675,048 | When using Qt in VS2008, IntelliSense does not work properly | I use Qt 4.4.2 in Visual Studio 2008.
When I am writing code, IntelliSense seems to die - it does not show any methods or data members in Qt objects such as QPushButton, does not see the QObject::connect static method, etc.
Is it a typical situation or did I do something wrong while installing the library?
| Most likely non-standard extensions like public slots: etc.
There's already a FAQ at the Qt site: Intellisense does not work for my Qt application. What's wrong?
|
675,039 | 675,095 | How can I create directory tree in C++/Linux? | I want an easy way to create multiple directories in C++/Linux.
For example I want to save a file lola.file in the directory:
/tmp/a/b/c
but if the directories are not there I want them to be created automagically. A working example would be perfect.
| Easy with Boost.Filesystem: create_directories
#include <boost/filesystem.hpp>
//...
boost::filesystem::create_directories("/tmp/a/b/c");
Returns: true if a new directory was created, otherwise false.
|
675,237 | 675,252 | Why use tuples instead of objects? | The codebase where I work has an object called Pair where A and B are the types of the first and second values in the Pair. I find this object to be offensive, because it gets used instead of an object with clearly named members. So I find this:
List<Pair<Integer, Integer>> productIds = blah();
// snip many lines and... | First of all, a tuple is quick and easy: instead of writing a class for every time you want to put 2 things together, there's a template that does it for you.
Second of all, they're generic. For example, in C++ the std::map uses an std::pair of key and value. Thus ANY pair can be used, instead of having to make some ki... |
675,259 | 693,840 | Avoiding too many configurations for a Visual Studio project | I'm currently porting a large Linux project to Visual Studio. The project depends on a number of third-party libraries (Python, MPI, etc.) as well as a couple of in-house ones. But it can also be built without these libraries, or with only a few of them. So I don't want to create a different configuration for each poss... | There's no good solution to this that I'm aware of. The IDE seems to require a configuration for each set of command line arguments to the tools. So if N different sets of arguments are required -- as it sounds like the case is here -- N different configurations will be required. That's just how the IDE works, it appea... |
675,362 | 675,383 | Best Practice for Scoped Reference Idiom? | I just got burned by a bug that is partially due to my lack of understanding, and partially due to what I think is suboptimal design in our codebase. I'm curious as to how my 5-minute solution can be improved.
We're using ref-counted objects, where we have AddRef() and Release() on objects of these classes. One parti... | use boost::shared_ptr
it is possible to define your own destructor function, such us in next example: http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/sp_techniques.html#com
|
675,614 | 675,701 | boost::asio::ip::tcp::resolver::resolve() blocks forever | I'm trying to create something similar as this code found at the boost.asio examples.
socket.h:
class some_class {
private:
...
boost::asio::io_service io_service;
public:
some_class() {
/* This stuff isn't used in the example...
...but it doesn't change anything... */
... | It is probably blocking on the call to connect, after the printf.
stdout is line buffered by default, and since you do not have a \n at the end of your printf string, you will not see its output. When you kill the program, the buffer is being flushed, which is why you see the message then.
|
675,739 | 675,748 | Pushing vector of vectors | Is there anything wrong with pushing back a vector of vectors? like
typedef vector<Point> Polygon;
vector<Polygon> polys;
polys.push_back(some_poly);
All the elements in some_poly will be copied right?
I have a bug in my code and I can't seem to figure out what's wrong with it.
| Yes, that should work fine, as long as you have defined a copy constructor and assignment operator for your Point class (and ensured they're doing the right thing etc). std::vector will push just fine, so the bug must be elsewhere - obviously we'd need more details to help further.
There are performance implications if... |
675,811 | 675,954 | Splitting an STL vector | Let's say I have a (convex) polygon with vertices 0..n-1. I want to split this polygon in half, say, between verticies i and j. Vertices i and j should appear in both polygons.
As far as I can tell, there are only two cases. One where i < j, or when i > j. i is never equal to j (nor are they ever adjacent).
I'm storin... | As a side note:
You don't really have 2 cases. If i > j then just swap i and j. Then you are always in the case where i < j, assuming i != j.
I would probably code it like follows:
if (i > closestIndex)
std::swap (i, closestIndex);
assert(closestIndex - i > 1);
// make sure i != closestIndex and i is not adjacent... |
675,817 | 675,839 | How do I create an array in C++ which is on the heap instead of the stack? | I have a very large array which must be 262144 elements in length (and potentially much larger in future). I have tried allocating the array on the stack like so:
#define SIZE 262144
int myArray[SIZE];
However, it appears that when I try and add elements past a certain point, the values are different when I try to acc... | You'll want to use new like such:
int *myArray = new int[SIZE];
I'll also mention the other side of this, just in case....
Since your transitioning from the stack to the heap, you'll also need to clean this memory up when you're done with it. On the stack, the memory will automatically cleanup, but on the heap, you'l... |
675,976 | 675,993 | MSVC++: Strangeness with unsigned ints and overflow | I've got the following code:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string a = "a";
for(unsigned int i=a.length()-1; i+1 >= 1; --i)
{
if(i >= a.length())
{
cerr << (signed int)i << "?" << endl;
return 0;
}
}
}
If I c... | I remember having this problem in 2001. I'm amazed it's still there. Yes, this is a compiler bug.
The optimiser is seeing
i + 1 >= 1;
Theoretically, we can optimise this by putting all of the constants on the same side:
i >= (1-1);
Because i is unsigned, it will always be greater than or equal to zero.
See this news... |
675,980 | 744,313 | SDL/C++ OpenGL Program, how do I stop SDL from catching SIGINT | I am using SDL for an OpenGL application, running on Linux. My problem is that SDL is catching SIGINT and ignoring it. This is a pain because I am developing through a screen session, and I can't kill the running program with CTRL-C (the program the computer is running on is connected to a projector and has no input de... | Ctrl-C at the console generates an SDL_QUIT event. You can watch for this event using SDL_PollEvent or SDL_WaitEvent, and exit (cleanly) when it is detected.
Note that other actions can generate an SDL_QUIT event (e.g. attempting to close your main window via the window manager).
|
676,385 | 676,404 | stdafx.h: When do I need it? | I see so much code including stdafx.h. Say, I do not want pre-compiled headers. And I will include all the required system headers myself manually. In that case is there any other good reason I should be aware of where I require stdafx.h?
| If you don't want to use precompiled headers, then there is no point to using a standard include file - this will slow down the build for every file that includes it and cause them to include extra stuff that they do not need. Get rid of it and just include the headers they need.
|
676,575 | 676,590 | Seg fault after is item pushed onto STL container | typedef struct temp
{
int a,b;
char *c;
temp(){ c = (char*)malloc(10);};
~temp(){free(c);};
}temp;
int main()
{
temp a;
list<temp> l1;
l1.push_back(a);
l1.clear();
return 0;
}
giving segmentation fault.
| You don't have a copy constructor.
When you push 'a' into the list, it gets copied.
Because you don't have a copy constructor (to allocate memory for c and copy from old c to new c) c is the same pointer in a and the copy of a in the list.
The destructor for both a's gets called, the first will succeed, the second will... |
676,797 | 676,813 | Memory management while loading huge XML files | We have an application which imports objects from an XML. The XML is around 15 GB. The application invariably starts running out of memory. We tried to free memory in between operations but this has lead to degrading performance. i.e it takes more time to complete the import operation. The CPU utilization reaches 100%
... | Have you tried resuing the memory and your classes as opposed to freeing and reallocating it? Constant allocation/deallocation cycles, especially if they are coupled with small (less than 4096 bytes) data fragments can lead to serious performance problems and memory address space fragmentation.
|
676,915 | 677,119 | Speed of virtual call in C# vs C++ | I seem to recall reading somewhere that the cost of a virtual call in C# is not as high, relatively speaking, as in C++. Is this true? If so - why?
| A C# virtual call has to check for “this” being null and a C++ virtual call does not. So I can’t see in generally why a C# virtual calls would be faster. In special cases the C# compiler (or JIT compiler) may be able to inline the virtual call better then a C++ compiler, as a C# compiler has access to better type inf... |
677,041 | 713,592 | Connect to Exchange - Getting Started Tutorial? | I need to connect to an Exchange-Server and to read some values, that a third party application stores there (BlackBerry Enterprise Server).
In my understanding I need to use CDO with C++ (C# doesn't seem to work this well in this regard). Is that right? I tried searching a little, but there seems to be lot of differe... | Thanks for the answers guys!
However I ended up downloading a little tool called MFCMapi from codeplex and using the provided source code as a guide on how to do things.
|
677,106 | 678,826 | Visual Studio 2005 - C++ - What controls the manifest creation | I was trying to figure out why a debug build was blowing up with the "dependent assembly microsoft.vc80.debugcrt could not be found" event error.
After deleting everything (anything not .cpp or .h) and recreating the solution - I still had the problem.
A google search was fruitless and a re-install of VS didn't produce... | The version was picked up by from the Boost DLLs which were a download, pre-compiled version of Boost. Once the libraries were re-compiled (and re-installed) a re-build of the solution produced a manifest with a single version and the program linked and ran.
So -Check the libs and dlls that are imported into the solut... |
677,325 | 677,331 | C++ - 2 classes 1 file | Suppose I want something of this sort, in one .cpp source file:
class A {
public:
void doSomething(B *b) {};
};
class B {
public:
void doSomething(A *a) {};
};
Is there anyway of doing this without splitting it into two separate files, and without receiving a compiler error (syntax error on do... | put at the first line:
class B;
|
677,444 | 678,904 | Why is my C++ code causing a segmentation fault well after using the read(...) function? | My application is suspending on a line of code that appears to have nothing wrong with it, however my IDE appears to be suspending on that line with the error:
gdb/mi (24/03/09 13:36) (Exited. Signal 'SIGSEGV' received. Description: Segmentation fault.)
The line of code simply calls a method which has no code in it. ... | Your code is bogus: buffer points to some random piece of memory. I'm not sure why the line with bzero is not failing.
The correct code is:
char buffer[BUFFER_SIZE];
bzero(buffer, BUFFER_SIZE);
int readResult = read(socketFD, buffer, BUFFER_SIZE);
or you can use calloc(1, BUFFER_SIZE) to get some memory all... |
677,620 | 677,626 | Do I need to explicitly call the base virtual destructor? | When overriding a class in C++ (with a virtual destructor) I am implementing the destructor again as virtual on the inheriting class, but do I need to call the base destructor?
If so I imagine it's something like this...
MyChildClass::~MyChildClass() // virtual in header
{
// Call to base destructor...
this->My... | No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.
|
677,632 | 677,642 | Different methods for instantiating an object in C++ | What is the difference between this:
Myclass *object = new Myclass();
and
Myclass object = new Myclass();
I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?
| The second is wrong !
You may use
MyClass object;
That will work.
Now, concerning how to choose between these two possibilities, it mainly depends on how long your object should live. See there for a thorough answer.
|
677,653 | 677,661 | Does delete on a pointer to a subclass call the base class destructor? | I have an class A which uses a heap memory allocation for one of its fields. Class A is instantiated and stored as a pointer field in another class (class B.
When I'm done with an object of class B, I call delete, which I assume calls the destructor... But does this call the destructor of class A as well?
Edit:
From t... | The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, ... |
677,722 | 677,749 | Navigate from a process to it's parent | I'm stuck with the process model of IE8, where a GetWindowThreadProcessId() for my MFC embedded window will give me a child IE PID, as the GetWindowThreadProcessId() for my container page will give me the root IE PID.
Which is bad, as I want to filter my container out, while enumerating windows.
So I'm looking for a w... | Have you seen this codeproject article or this codeguru article?
I think the better method is in the codeguru article.
Basically you want the "ULONG InheritedFromUniqueProcessId" member of PROCESS_BASIC_INFORMATION. See NtQueryInformationProcess and this page.
|
677,812 | 677,819 | Is there a reason to call delete in C++ when a program is exiting anyway? | In my C++ main function, for example, if I had a pointer to a variable which uses heap memory (as opposed to stack memory) - is this automatically deallocated after my application exits? I would assume so.
Even so, is it good practice to always delete heap allocations even if you think they will never be used in a situ... | It is important to explicitly call delete because you may have some code in the destructor that you want to execute. Like maybe writing some data to a log file. If you let the OS free your memory for you, your code in your destructor will not be executed.
Most operating systems will deallocate the memory when your pr... |
677,866 | 688,527 | Building Elsa on windows | How would I build elsa under windows?
http://www.eecs.berkeley.edu/~smcpeak/elkhound/sources/elsa/
A visual studio would be preferable or something I can link with using visual studio,
| Try compile it under Cygwin.
Download the Cygwin install, select GCC and Flex, Perl, etc. Install that stuff, then follow the normal build process, once in Cygwin.
|
677,913 | 677,932 | remove elements with specific value from std::list | I need to remove elements with specific value from std::list. With the list<int> I used remove() method.
Now I have list<CMyClass> so I thought I should use remove_if() but it's predicate takes only one paramater - the element to be tested.
How do I write a function foo(const CMyClass &Bad) which removes from list all ... | Your class has to implement operator == in your ClassName
bool operator == ( const Class& rhs );
and then you can use
list.remove( Bad )
If it is reasonable to your class to have operator == ( not just for remove ) - than list::remove is good for you solution. If operator == only for list::remove than it is better t... |
678,325 | 678,330 | Remove file in C++ under UNIX | How do you guys typically delete files on Linux OS? I am thinking of using the unlink function call, but I wonder if you have a better idea, as the C++ standard has no mention of file deletion operation and it is system dependent.
| Yep -- the C++ standard leaves this stuff up to the OS, so if you're on Linux (or any POSIX system), unlink() is what you've got.
The C standard provides remove(), which you could try, but keep in mind that its behavior is unspecified for anything other than a 'regular file', so it doesn't really shield you from gett... |
678,944 | 678,957 | How do I create a TCP server that will accept only one connection at a time? | I'm writing a client-server pair in C++ using Linux sockets. I want the server to listen for a connection, and while one client is connected the server should reject any other clients that try to connect.
I tried implementing this by setting the backlog parameter in the listen function to 0 and to 1 and neither one of... | When you accept a connection, a new socket gets created. The old one is still used to listen for future connections.
Since you want to only allow 1 connection at a time, you could just accept the connections, and then close the new accepted socket if you detect you are already processing another.
Is there a net diffe... |
678,956 | 678,985 | What is the best free portable 3d/2d engine? | i like to make very simple 3d/2d game for pc/mac/linux
what is the best free 3d/2d engine for this ?
i have no experience in game programming so i guess it have to be easy to learn
please in c++
thanks
| While 'best' can very much depend on your situation, one I have used in the past to great success is OGRE 3D.
It's cross-platform, very nicely written (C++), and runs well. However the one thing that set it apart for me was the great community - you can always get help no matter how simple your question, and there are ... |
679,021 | 679,040 | How to find the name of the current function at runtime? | After years of using the big ugly MFC ASSERT macro, I have finally decided to ditch it and create the ultimate ASSERT macro.
I am fine with getting the file and line number, and even the expression that failed. I can display a messagebox with these in, and Abort/Retry/Cancel buttons.
And when I press Retry the VS debug... | Your macro can contain the __FUNCTION__ macro.
Make no mistake, the function name will be inserted into the expanded code at compile time, but it will be the correct function name for each call to your macro. So it "seems like" it happens in run-time ;)
e.g.
#define THROW_IF(val) if (val) throw "error in " __FUNCTION__... |
679,113 | 679,301 | Trouble porting OpenGL app to Windows | I am trying to move an OpenGL app to Windows.
It was my understanding that Windows had a decent OpenGL implementation. But I'm starting to think that it doesn't...
Specifically, I use array buffers and glDrawArrays.
When I tried to compile my code in Visual Studio 2008 Pro, I received the following errors:
vertexbuffer... | The #defines are commented out in the header file whenever they would otherwise be repeated. Look at line 1054 of gl.h:
/* vertex_array */
#define GL_VERTEX_ARRAY 0x8074
If this #define is actually missing then you should probably replace the file with a fresh copy.
If you look at the documentation f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.