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 also known as "3D Stereo", primarily by nVidia (I think).
Does anyone see stereoscopy as a major technology in terms of how we visualize things? I'm talking in both a recreational and professional capacity.
|
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. Right now all you need is 120Hz LCD, entry level graphics card and $100 shutter glasses.
So no doubt about it, it will be the next big thing. At least in entertainment.
|
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 strategies to implement block and underscore caret.
Off Topic: Is this a bug? StackOverflow says there are two answers for this question but I'm seeing only one!
|
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 returned, shouldn't it create problems if object is declared locally in the function.
i mean the copy constructor is a deep copy one and takes reference of an object as parameter
|
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 constructor is called. It uses the passed reference to access the locally-defined object and copy what's necessary to the new object.
|
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; };
C f( int i, int d ) {
return C(i,d); // construct _and_ copy-construct?
}
int main() {
C c = f( 1, 2 );
}
|
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 has the old value;
The solution is quite simple:
void B()
{
ObjType * o = getObj();
o->set("abc");
}
This does work. But to me, this is quite the same as the first sample. Can anyone explain this?
|
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 and SA.cpp, and the second CFE.c.
A class called 'SimAnneal' exsists in SA.cpp, with public vectors DensityArray and ElementArray. The order of the program follows:
Create SimAnneal Object 'Obj1' and call function ObjFunction()
That function initializes the vector sizes
Call CFE(...) with pointers to both vectors and their length.
CFE.c edits the data elements of the vectors directly via use of the pointers
ObjFunction() uses EnergyArray (and possible DensityArray) data.
The relevant script is below for all sources:
main.cpp
#include "SA.h"
int main()
{
SimAnneal Obj1;
Obj1.ObjFunction();
return 0;
}
SA.h
class SimAnneal
{
void Initialize ();
...
public
std::vector<float> DensityArray;
std::vector<float> EnergyArray;
double ObjFunction ();
...
}
SA.cpp
#include "CFE.h"
void SimAnneal::Initialize ()
{
int length = 15;
EnergyArray.resize(length);
DensityArray.resize(length);
}
double SimAnneal::ObjFunction ()
{
Initialize ();
CFE(&DensityArray[0], &EnergyArray[0], DensityArray.size());
// sends pointers of both arrays to CFE.c, which will then
// directly modify the array
double SumStrainEnergy = 0;
for (int i = 0; i < EnergyArray.size(); i++)
{
SumStrainEnergy += EnergyArray[i]; //Effectively sum of array
//engy[] from CFE.c
}
return SumStrainEnergy;
}
CFE.h
#ifdef __cplusplus
extern "C" {
#endif
void CFE(float density[], float energy[], int NumElem);
#ifdef __cplusplus
}
#endif
CFE.c
void CFE(float density[], float energy[], int NumElem)
{
...
float * dens;
dens = density; //pass pointer of array density[0] in SA.cpp to CFE.c
for(n=0; n<NumElem; n++)
{ ... modify dens (e.g. DensityArray from SA.cpp) ... }
float * engy;
engy = energy; //pass pointer of array energy[0] in SA.cpp to CFE.c
for(n=0; n<NumElem; n++)
{ ... modify engy (e.g. EnergyArray from SA.cpp) ... }
}
Am I causing an illegal memory access by trying to access the vector elements from the C portion of my program? Is there any sure way to allow this?
Any help would be much appriciated.
|
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++ the Technical Corrigendum 2003 at present, but apparently the relevant section ref is 23.2.4,
|
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)
{
cout << "Receiving chunk... ";
// Read a bit at a time, eventually "end" string will be received.
bzero(buffer, BUFFER_SIZE);
int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE);
if (readResult < 0)
{
THROW_VIMRID_EX("Could not read from socket.");
}
// Concatenate the received data to the existing data.
readStream << buffer;
// Continue reading while end is not found.
readData = readStream.str().find("end;") == string::npos;
cout << "Done (length: " << readStream.str().length() << ")" << endl;
}
It's a little bit of C and C++ as you can tell. The BUFFER_SIZE is 256 - should I just increase the size? If so, what to? Does it matter?
I know that if "end" is not received for what ever reason, this will be an endless loop, which is bad - so if you could suggest a better way, please also do so.
|
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 of the rest of your message. Then simply do the following.
// This assumes buffer is at least x bytes long,
// and that the socket is blocking.
void ReadXBytes(int socket, unsigned int x, void* buffer)
{
int bytesRead = 0;
int result;
while (bytesRead < x)
{
result = read(socket, buffer + bytesRead, x - bytesRead);
if (result < 1 )
{
// Throw your error.
}
bytesRead += result;
}
}
Then later in the code
unsigned int length = 0;
char* buffer = 0;
// we assume that sizeof(length) will return 4 here.
ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);
// Then process the data as needed.
delete [] buffer;
This makes a few assumptions:
ints are the same size on the sender and receiver.
Endianess is the same on both the sender and receiver.
You have control of the protocol on both sides
When you send a message you can calculate the length up front.
Since it is common to want to explicitly know the size of the integer you are sending across the network define them in a header file and use them explicitly such as:
// These typedefs will vary across different platforms
// such as linux, win32, OS/X etc, but the idea
// is that a Int8 is always 8 bits, and a UInt32 is always
// 32 bits regardless of the platform you are on.
// These vary from compiler to compiler, so you have to
// look them up in the compiler documentation.
typedef char Int8;
typedef short int Int16;
typedef int Int32;
typedef unsigned char UInt8;
typedef unsigned short int UInt16;
typedef unsigned int UInt32;
This would change the above to:
UInt32 length = 0;
char* buffer = 0;
ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);
// process
delete [] buffer;
I hope this helps.
|
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(dllimport) B<int>;
|
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 ?
Here's a brief summary of what I tested (and it worked):
Create a dummy DLL project
Used the Win32 Console application wizard to generate the dll header/source files called: template_export_test
Added the following:
file: template_export_test.h
#ifndef EXP_STL
#define EXP_STL
#endif
#ifdef EXP_STL
# define DECLSPECIFIER __declspec(dllexport)
# define EXPIMP_TEMPLATE
#else
# define DECLSPECIFIER __declspec(dllimport)
# define EXPIMP_TEMPLATE extern
#endif
EXPIMP_TEMPLATE template class DECLSPECIFIER CdllTest<int>;
file: template_export_test.cpp
template<class T>
CdllTest<T>::CdllTest(T t)
: _t(t)
{
std::cout << _t << ": init\n";
}
Create the test application
Use the wizard to create a Win32 Console application called: driver
Edit the Linker project settings of this project:
Add to Linker > General > Additional Library Directories: path to template_export_test.lib
Add to Linker > Input > Additional Dependencies: template_export_test.lib
Include the template_export_test.h in the main cpp file
#include "c:\Documents and Settings\...\template_export_test.h"
using namespace std;
int main(int argc, char** argv) {
CdllTest<int> c(12);
}
Compile and go!
|
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? At the moment I have the following in stdafx.h which I guess creates a manifest file on the fly:
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
Can I modify this line to force the elevation or do I need to do something with the VC project manifest settings?
Thanks in advance.
|
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 properties.
|
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(...) in C segments. Depending on which order I run these at I always get segmentation error when using the 2nd type, like so:
cout first, then printf(...) will crash at first C output function
printf(...), then cout will crash at first C++ output function
I am #include <iostream> in my C++ sources, and #include <stdio.h> & #include <stdlib.h> in my C sources.
Is there a library conflict that I am not aware of?
Requested code:
main.cpp
#include <iostream>
#include <vector>
#include "CFE.h"
ios::sync_with_stdio(true);
using namespace std;
vector<float> DensityArray;
vector<float> EnergyArray;
int main()
{
int X = ReturnX ();
int Y = ReturnY ();
cout << "X " << X << endl;
cout << "Y " << Y << endl;
EnergyArray.resize(Y*X);
DensityArray.resize(Y*X);
CFE(&DensityArray[0], &EnergyArray[0]);
cout << "X " << X << endl; //causes Segmentation break
cout << "Y " << Y << endl; //causes Segmentation break
system ("PAUSE");
return 0;
}
CFE.h
#ifdef __cplusplus
extern "C" {
#endif
int ReturnX ();
int ReturnY ();
void CFE(float density[], float energy[]);
#ifdef __cplusplus
}
#endif
CFE.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "BCs.h"
#include "EMatrix.h"
#include "Numbering.h"
#include "KMatrix.h"
#include "fg_types.h"
#include "Solve.h"
int ReturnX ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
fclose(infile);
return elemX;
}
int ReturnY ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
fclose(infile);
return elemY;
}
void CFE(float density[], float energy[])
{
FILE *infile;
infile = fopen("test05", "r");
int elemY, elemX;
fscanf(infile, "%i %i", &elemX, &elemY); //Will cause Segmentation break
int n;
float * dens;
dens = density;
float * engy;
engy = energy;
int Length = 10;
for ( n = 0; n < Length; n++)
{
engy[n] = n;
}
}
|
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 resides after installing it through macports), but all i get is:
Undefined symbols: "_MP4Read",
referenced from:
_main in main.o ld: symbol(s) not found
Even though XCode finds it and autocompletes properly...
|
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 x;
string Filename = "my.bin" ;
fp = fopen(Filename.c_str(),"rb");
if (fp == NULL)
{
cout << "File not found" << endl ;
}
if (fseek (fp, 0, SEEK_END) != 0)
{
cout <<"End of File can't be seeked";
return -1;
}
if ( (fileLength = ftell(fp)) == -1)
{
cout <<"Can't read current position of file";
return -1;
}
if (fseek (fp, 0, SEEK_SET) != 0)
{
cout <<"Beginning of File can't be seeked";
return -1;
}
if (fread(&x,sizeof(x),1,fp) != sizeof(x))
{
cout <<"file not read correctly";
return -1;
}
|
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 tell you if call succeeded.
Going through the process of actually reducing your faulty code to the absolute but complete minimum to reproduce the error is the first thing you should do when a piece of code has you dumbfounded.
It might (and usually does) turn out that the problem isn't even where you thought it is.
That being said, I'd try replacing
if (fread(&x,sizeof(x),1,fp) != sizeof(x))
{
cout <<"file not read correctly";
return -1;
}
with
int i;
if ( ( i = fgetc( fp ) ) == EOF )
{
perror( "File not read correctly" );
return -1;
}
x = (char) i;
cout << "Success, read '" << x << "'." << endl;
Using 'perror()' instead of homebrewn cout messages gives you additional information on the cause of any error. Using 'fgetc()' will show you that the file actually does contain what you think it does, and that your problems are not due to the somewhat uncommon use of fread() for a single byte.
Then report back.
|
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 in case when parameter is non const reference.
Last line of FAQ says
"Note that if a function accepts a parameter by non-const reference (for example, f(string& s)), returning a copy of this reference parameter is safe because a temporary cannot be passed by non-const reference."
Need some insight on this!!
|
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:
temporary Foo is allocated
bar is called with a reference to the temporary object
bar returns the reference
now that bar has returned the temporary Foo is released
the reference is now dangling as the object was destroyed
However, if you had Foo declared as
Foo & bar(Foo &f) { return f; }
then your call bar(Foo()) would not be accepted by compiler. When you pass a temporary object to a function, you can only take it by const reference or as a copy; this is part of the language definition.
|
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 if they are just meant to contain an integer: in this case having a virtual pointer in every instance might double the size of the instances. As for the memory space used up by the virtual tables, I guess it is usually negligible compared to the space used up by the actual method code.
This brings me to my question: is there a measurable performance cost (i.e. speed impact) for making a method virtual? There will be a lookup in the virtual table at runtime, upon every method call, so if there are very frequent calls to this method, and if this method is very short, then there might be a measurable performance hit? I guess it depends on the platform, but has anyone run some benchmarks?
The reason I am asking is that I came across a bug that happened to be due to a programmer forgetting to define a method virtual. This is not the first time I see this kind of mistake. And I thought: why do we add the virtual keyword when needed instead of removing the virtual keyword when we are absolutely sure that it is not needed? If the performance cost is low, I think I will simply recommend the following in my team: simply make every method virtual by default, including the destructor, in every class, and only remove it when you need to. Does that sound crazy to you?
|
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 inline is kind of wasteful. A 7ns overhead on a function that inlines to 0.5ns is severe; a 7ns overhead on a function that takes 500ms to execute is meaningless.
The big cost of virtual functions isn't really the lookup of a function pointer in the vtable (that's usually just a single cycle), but that the indirect jump usually cannot be branch-predicted. This can cause a large pipeline bubble as the processor cannot fetch any instructions until the indirect jump (the call through the function pointer) has retired and a new instruction pointer computed. So, the cost of a virtual function call is much bigger than it might seem from looking at the assembly... but still only 7 nanoseconds.
Edit: Andrew, Not Sure, and others also raise the very good point that a virtual function call may cause an instruction cache miss: if you jump to a code address that is not in cache then the whole program comes to a dead halt while the instructions are fetched from main memory. This is always a significant stall: on Xenon, about 650 cycles (by my tests).
However this isn't a problem specific to virtual functions because even a direct function call will cause a miss if you jump to instructions that aren't in cache. What matters is whether the function has been run before recently (making it more likely to be in cache), and whether your architecture can predict static (not virtual) branches and fetch those instructions into cache ahead of time. My PPC does not, but maybe Intel's most recent hardware does.
My timings control for the influence of icache misses on execution (deliberately, since I was trying to examine the CPU pipeline in isolation), so they discount that cost.
|
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 find where I read this but I can't seem to locate anything - is there a way?
|
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 official compiler directive, is there a trick to make the compiler think that it's an important function? Or at least make it think that it can't safely be ignored? I tried something like this:
extern bool bar;
void foo(){
if(bar){
Foo<int> v;
}
}
but that didn't seem to do it.
(If you really want to know why I on earth would want that -- it has to do with this question, where, instead of explicit template instantiation with template class Foo<int> I simply want to be able to write Foo<int> v, since in many cases that's easier since it implicitly instantiates all functions needed, and it does work fine in debug mode without optimizations ...)
UPDATE:
Here is what I want to do (as a compilable mini example):
foo.h (such files are given to me and not changeable)
template<class T>
struct Foo {
T val_;
Foo(T val) : val_(val) {
// heavy code, long compile times
}
};
foo-instantiation.cpp
#include "foo.h"
void neverCalled() {
Foo<int> f(1);
}
// The standard way to instantiate it is this:
// template class Foo<int>;
// but in reality it is often hard to find out
// exactly what types I have to declare.
// Usage like Foo<int> f(1); will instantiate all
// dependent types if necessary.
foo-decl.h (an interface that I extracted from foo.h)
template<class T>
struct Foo {
T val_;
Foo(T val); // no heavy code, can include anywhere and compile fast
};
main.cpp
#include <iostream>
#include "foo-decl.h"
int main(int argc, char** argv){
Foo<int> foo(1);
return 0;
}
Compilation (no optimization)
g++ -c main.cpp
g++ -c foo-instantiation.cpp
g++ main.o foo-instantiation.oo
Compilation (optimization)
g++ -O2 -c main.cpp
g++ -O2 -c foo-instantiation.cpp
g++ main.o foo-instantiation.oo
main.o(.text+0x13): In function `main':
: undefined reference to `Foo<int>::Foo(int)'
collect2: ld returned 1 exit status
I tried precompiled headers instead, but the template instantiation method makes for much faster compilation.
Compiling foo-instantiation.cpp without optimization is not so ideal because then the library code (foo.h and others) will run slower.
|
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 anywhere and compile fast
};
This is explicitly not allowed in C++ (only one identical definition allowed) and if you break the rule your code may well seem to work sometimes, but what you actually have is the dreaded "undefined behaviour" - anything may happen depending on the phase of the moon (but more likely the internal state of the compiler at certain critical junctures).
Basically, you can't write code like that - sorry.
|
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 break before the call to SwapBuffers shows hdc's value to be:
0xfe011734 {unused=???}
CXX0030: Error: expression cannot be evaluated
Anyone have a clue what could be happening? Is there something about SwapBuffers that would change from one PC to the next? I've gotten it to work on XP32, XP64 and a (different) Vista64.
while (!quit)
{
if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
if (msg.message == WM_QUIT)
quit = true;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
renderFrame(); //draws the scene
SwapBuffers(hdc);
if (GetAsyncKeyState(VK_ESCAPE))
shutdown();
think(); //calculates object positions, etc.
}
The drivers on the problematic system (HD4850) are up-to-date. I've run, and wrote, the program on another Vista64 system with a Radeon HD4870, also with up-to-date drivers. As far as I know, the drivers for these two cards are nearly identical as both are in the HD48xx series. For that reason it seems odd that the GPU is causing the problem.
Anyway, am I wrong or is this a memory issue? (Access violation)
Also, if I remove the call to SwapBuffers(hdc), the program runs seemingly well, although nothing is drawn, of course, because the framebuffers are never swapped. But it is at least stable.
Call stack (-> is stack ptr):
ATKOGL32.dll!6aef27bc()
opengl32.dll!665edb2d()
opengl32.dll!665f80d1()
gdi32.dll!75e14104()
-> MyProg.exe!WinMain(HINSTANCE__ * hinstance=0x009a0000, HINSTANCE__ * hprevinstance=0x00000000, char * lpcmdline=0x003b4a51, int nshowcmd=1) Line 259 + 0xe bytes
MyProg.exe!__tmainCRTStartup() Line 578 + 0x35 bytes
MyProg.exe!WinMainCRTStartup() Line 400
kernel32.dll!7641e3f3()
ntdll.dll!777dcfed()
ntdll.dll!777dd1ff()
Heres the assembly (-> is the next instruction to be executed):
SwapBuffers(hdc);
009B1B5C mov esi,esp
009B1B5E mov eax,dword ptr [hdc (9BF874h)]
009B1B63 push eax
009B1B64 call dword ptr [__imp__SwapBuffers@4 (0E1040Ch)]
-> 009B1B6A cmp esi,esp
009B1B6C call @ILT+780(__RTC_CheckEsp) (9B1311h)
|
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 driver and that's where the crash happens. You might want to install stock ATI drivers from amd.com and see if the crash still persists.
While the driver should never crash no matter what series of OpenGL calls you make, in my experience usually the crashes are the result of some kind of invalid call that your program makes. Technically this should just be ignored and the error state set but thats not always what happens. You can check for any invalid OpenGL calls easily by using a program like gDebugger.
|
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 it would be easier to simply use qmake as my build system. Hence, adding my old project build process to the .pro file and use that to generate a new .xcodeproj? I would only do this if I could comprehensively configure the .pro file so that I don't have to hand configure the .xcodeproj - is this doable? I really don't want to have to mess around with hand configuring the .xcodeproj each time I run qmake.
Essentially, is qmake (or a meta-build in general) a valid substitute for a normal build system, such that I don't need to tweak the resulting build system generated by qmake?
Are there better resources besides the manual and tutorial provided by Trolltech? I'm concerned that wikipedia says that qmake is primarily for internal use and not well documented.
|
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 not manifold examples like there are for make. But, it is similar to make and should be intuitive. Why not absorb the overhead to learn it and pass the benefit on to your users/developers?
|
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 without using conditionals. Maybe someone has got some thoughts about it.
Thanks
|
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 setne %al
a: 09 d0 or %edx,%eax
c: 83 e0 01 and $0x1,%eax
f: c3 retq
0000000000000010 <bar>:
10: f7 d7 not %edi
12: 09 fe or %edi,%esi
14: 89 f0 mov %esi,%eax
16: c3 retq
So, no branches, but twice as many instructions.
And even better, with _Bool (thanks @litb):
_Bool baz(_Bool a, _Bool b) { return !a || b; }
0000000000000020 <baz>:
20: 40 84 ff test %dil,%dil
23: b8 01 00 00 00 mov $0x1,%eax
28: 0f 45 c6 cmovne %esi,%eax
2b: c3 retq
So, using _Bool instead of int is a good idea.
Since I'm updating today, I've confirmed gcc 8.2.0 produces similar, though not identical, results for _Bool:
0000000000000020 <baz>:
20: 83 f7 01 xor $0x1,%edi
23: 89 f8 mov %edi,%eax
25: 09 f0 or %esi,%eax
27: c3 retq
|
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 inheritance in the real code):
class CWaitable
{
public:
void WakeWaiters() const
{
CDifferentClass::Get()->DoStuff(this); // Breakpoint here
}
};
class CMotion : public CWaitable
{
virtual void NotUsedInThisExampleButPertinentBecauseItsVirtual() { }
};
class CMotionWalk : public CMotion
{ ... };
void AnnoyingFunctionThatBreaks(CMotion* pMotion)
{
pMotion->WakeWaiters();
}
Okay, so I call "AnnoyingFunctionThatBreaks" with a "CMotionWalk" instance (e.g. the debugger says it's 0x06716fe0), and all seems well. But when I step into it, to the breakpoint on the call to "DoStuff", the 'this' pointer has a different value to the pMotion pointer I called the method on (e.g. now the debugger says one word higher - 0x06716fe4).
To phrase it differently:
pMotion has the value 0x06716fe0, but when I call a method on it, that method sees 'this' as 0x06716fe4.
I'm not just going mad am I? That is weird, right?
|
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 crashes, and there are no pointers outside the objects) then I wouldn't worry about it too much.
|
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_sim_Open = simFileToOpen.copy();
SysFreeString(simFileToOpen);
delete simFile;
hresult = pis8->raw_Open (raw_sim_Open); //0x8000FFFF returned
|
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 to get a BSTR directly.
BSTR str = SysAllocString(_T("path"));
|
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));
MessageBox(0,buf,"info",0);
WSACleanup();
return 0;
}
This program is for getting information of available wsock version in the computer.
I cannot understand why "stdafx.h" is included in program.
What's the significance of APIENTRY? Can't we use _stdcall instead?
I also can't compile it in VC++. What's the problem with the code?
Below are the errors when executing program there are no errors during compiling.
--------------------Configuration: sa - Win32 Debug--------------------
Linking...
sa.obj : error LNK2001: unresolved external symbol _WSACleanup@0
sa.obj : error LNK2001: unresolved external symbol _WSAStartup@8
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/sa.exe : fatal error LNK1120: 3 unresolved externals
Error executing link.exe.
sa.exe - 4 error(s), 0 warning(s)
|
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 for example). It's to make your code more portable.
Without the actual errors you are getting, I'm not going to be able to help much. But my first guess is that you have unicode on in your build and it's complaining that MessageBoxW doesn't take a char[100] as an argument. In this case, either use wide chars everywhere, or turn off unicode, or use MessageBoxA to explicitly use the ASCII version.
Edit:
Now with the errors, it's easy. Under Project properties -> Linker -> Input -> Additional Dependencies, add ws2_32.lib. So you can get the Winsock functions linked in.
The missing _main indicates that you are building the app as a console app, and not a windows app. Go back to project Properties -> Linker -> System and set SubSystem to Windows (/Subsystem:Windows) instead of Console. Or else, just rename WinMain to int main() (Make sure you drop the APIENTRY).
Also, if you're using MSVC++ you might as well use the safer sprintf_s:
sprintf_s(buf,100,"%d.%d",HIBYTE(ws.wVersion),LOBYTE(ws.wVersion));
|
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
foo->say_virtual_hi(); // will crash the app
return 0;
}
I know that the virtual method call crashes because it requires a vtable lookup and can only work with valid objects.
I have the following questions
How does the non virtual method say_hi work on a NULL pointer?
Where does the object foo get allocated?
Any thoughts?
|
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 caller needs to know which object the function is being called on. That's because the object itself is what tells which function should really be called. (That's frequently implemented by giving the object a pointer to a vtable, a list of function-pointers, and the caller just knows it's supposed to call the first function on the list, without knowing in advance where that pointer points.)
But to call a non-virtual function, the caller doesn't need to know all that. The compiler knows exactly which function will get called, so it can generate a CALL machine-code instruction to go directly to the desired function. It simply passes a pointer to the object the function was called on as a hidden parameter to the function. In other words, the compiler translates your function call into this:
void Foo_say_hi(Foo* this);
Foo_say_hi(foo);
Now, since the implementation of that function never makes reference to any members of the object pointed to by its this argument, you effectively dodge the bullet of dereferencing a null pointer because you never dereference one.
Formally, calling any function — even a non-virtual one — on a null pointer is undefined behavior. One of the allowed results of undefined behavior is that your code appears to run exactly as you intended. You shouldn't rely on that, although you will sometimes find libraries from your compiler vendor that do rely on that. But the compiler vendor has the advantage of being able to add further definition to what would otherwise be undefined behavior. Don't do it yourself.
|
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 static library, each one has its own copy of myGlobal. work() would modify its own version of the variable.
My question now: is there a way to get a process-wide unique variable or pointer to that variable? Similar what thread-local storage would be for thread-wide variables. It doesn't have to be platform independent. Bonus points if it works in Win32 :)
|
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().sendAt(msg->sapindex0());
bouncer_comm returns an RTOutSignal, I can't create them manually because of the bizarre structure rose uses.
Right now, my only option is to create a hundred or so if statements, where I do:
if(action == "CHAT") bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
Which is realllllyy annoying.
What would be the best way to avoid this? I've looked at / tried countless things, this is a really old version of rational rose (pre 2k) and yeah.
If anyone has any ideas that would be amazing.
|
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 which is better to use? Is there something else I'm missing?
|
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 libc function time_t time (time_t *result);
If result is not NULL, the current time will be stored. But if result is NULL, then no action is taken.
If the function that you're writing doesn't need to use NULL as a meaningful value then using references (ie. the '&') will probably be less confusing - assuming that is the convention that your project uses.
|
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_array() functionality.
As a side question, if I don't need the c_array() method, what is the best way to approach this problem if I need random access? Should I use a deque or something else?
Edit:
I do need dynamic sizing.
For those who don't know, vector<bool> is specialized so that each bool takes 1 bit. Thus you can't convert it to a C-style array.
I guess "wrapper" is a bit of a misnomer. I was thinking something like this:
Of course, then I have to read into a my_bool due to possible alignment issues :(
struct my_bool
{
bool the_bool;
};
vector<my_bool> haha_i_tricked_you;
|
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, ss2;
Tee my_split(ss1, ss2); // redirects to both streams
my_split << "Testing";
assert(ss1.str() == "Testing" && ss1.str() == ss2.str());
But it won't compile in VC9:
c:\lib\boost_current_version\boost\iostreams\stream.hpp(131) : error C2665: 'boost::iostreams::tee_device<Sink1,Sink2>::tee_device' : none of the 2 overloads could convert all the argument types
Has anyone gotten this to work? I know I could make my own class to do it, but I want to know what I am doing wrong.
Thanks
|
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:
Each of these members constructs an instance of stream and associates it with an instance of the Device T constructed from the given lists of arguments. The T constructors involved must take all arguments by value or const reference.
Well, but the tee_device constructor says
Constructs an instance of tee_device based on the given pair of Sinks. Each function parameter is a non-const reference if the corresponding template argument is a stream or stream buffer type, and a const reference otherwise.
That won't work, of course. io::stream provides another constructor that takes a T as first argument. This works here (Compiles, at least. The assertion fails, though. I've not worked with boost::iostreams so i can't help with that)
namespace io = boost::iostreams;
typedef io::tee_device<std::stringstream, std::stringstream> TeeDevice;
typedef io::stream< TeeDevice > TeeStream;
std::stringstream ss1, ss2;
TeeDevice my_tee(ss1, ss2);
TeeStream my_split(my_tee);
my_split << "Testing";
assert(ss1.str() == "Testing" && ss1.str() == ss2.str());
Edit: After calling flush() or streaming << std::flush, the assertion passes.
|
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 in motion by calling start/stop.
void somewhere() {
foo* hihi = new foo;
hihi->start();
delete hihi;
}
Then there's bar.h:
#ifndef _BAR_H_
#define _BAR_H_
class bar {
};
#endif // _BAR_H_
g++ doesn't seem to like it however:
g++ (some_flags) -c main.cpp
In file included from main.cpp:2:
foo.h:8: error: ‘bar’ does not name a type
I'm using makefiles, and tried a combination of things like:
main.o: main.cpp foo.h bar.h
Even though I don't think I should have to add bar.h here, shouldn't including it in foo.h be enough?
To clarify, this is roughly how it's set up now (yes I know this can be done in a more efficient manner):
main.o: main.cpp foo.h
$(CC) $(CFLAGS) -c main.cpp
foo.o: foo.h foo.cpp
$(CC) $(CFLAGS) -c foo.cpp
bar.o: bar.h bar.cpp
$(CC) $(CFLAGS) -c bar.cpp
What's going on? I figure it's something I'm missing about g++ and the way it handles header includes, point me in the right direction please!
edit - found the solution:
Doh! I feel dumb right now.
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 :D
Oh well, thanks anyway!
|
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 run into real life situation where typedefing a class would have probably helped you find your problem a little easier:
class bar {
// ...
};
typedef class bar bar;
Generates this more meaningful message if there's a function named bar() already declared:
In file included from C:\temp\foo.h:4,
from C:\temp\test.cpp:4:
C:\temp\bar.h:7: error: `typedef class bar bar' redeclared as different kind of symbol
C:\temp\test.cpp:1: error: previous declaration of `void bar(int)'
C:\temp\bar.h:7: error: declaration of `typedef class bar bar'
|
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; // access via pointer to member
cout << "speed is " << c1.speed << endl;
return 0;
}
As to why you would want to do that, well it gives you another level of indirection that can solve some tricky problems. But to be honest, I've never had to use them in my own code.
Edit: I can't think off-hand of a convincing use for pointers to member data. Pointer to member functions can be used in pluggable architectures, but once again producing an example in a small space defeats me. The following is my best (untested) try - an Apply function that would do some pre &post processing before applying a user-selected member function to an object:
void Apply( SomeClass * c, void (SomeClass::*func)() ) {
// do hefty pre-call processing
(c->*func)(); // call user specified function
// do hefty post-call processing
}
The parentheses around c->*func are necessary because the ->* operator has lower precedence than the function call operator.
|
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 passed to the compiler, but it doesn't show the name of the compiler itself.
|
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 / Mobile Command Line Compiler: http://msdn.microsoft.com/en-us/library/aa448630.aspx
|
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)),
cvCloneMat(getData->getMasterRawMat(3)),
cvCloneMat(getData->getMasterRawMat(4)) );
imageWin->show();
How do I deallocate ( where do I call cvReleaseMat ), when the new window is closed?
|
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 memory allocated to process or thread in case of a[11] or a[25] and it's going out of stack bounds in case of a[20000].
Why doesn't compiler or linker give an error, aren't they aware of the array size? If not then how does sizeof(a) work correctly?
|
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 simply access another part of the already allocated stack space (most OS's and threads reserve a certain portion of memory for stack). As long as you just happen to be playing around in the pre-allocated stack space, everything will not crash (note i did not say work).
What's happening on the last line is that you have now accessed beyond the part of memory that is allocated for the stack. As a result you are indexing into a part of memory that is not allocated to your process or is allocated in a read only fashion. The OS sees this and sends a seg fault to the process.
This is one of the reasons that C/C++ is so dangerous when it comes to boundary checking.
|
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 implementation):
template<class T> class RelationalOperatorsImpl
{
protected:
RelationalOperatorsImpl() {}
~RelationalOperatorsImpl() {}
friend bool operator!=(const T& lhs, const T& rhs) {return !(lhs == rhs);}
friend bool operator>(const T& lhs, const T& rhs) {return (rhs < lhs);}
friend bool operator<=(const T& lhs, const T& rhs) {return !(rhs < lhs);}
friend bool operator>=(const T& lhs, const T& rhs) {return !(lhs < rhs);}
};
template<typename T> class Foo : RelationalOperatorsImpl< Foo<T> >
{
public:
explicit Foo(const T& value) : m_Value(value) {}
friend bool operator==(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value == rhs.m_Value);}
friend bool operator<(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value < rhs.m_Value);}
private:
T m_Value;
};
[2] std::rel_ops glue:
template<typename T> class Foo
{
public:
explicit Foo(const T& value) : m_Value(value) {}
friend bool operator==(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value == rhs.m_Value);}
friend bool operator<(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value < rhs.m_Value);}
private:
T m_Value;
};
void Consumer()
{
using namespace std::rel_ops;
//Operators !=, >, >=, and <= will be instantiated for Foo<T> (in this case) on demand.
}
I'm basically trying to avoid code repetition. Any thoughts as to which method "feels" better?
|
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 use it already, you should seriously consider start using it), the con factor is dimmed.
|
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++, etc. The C++ code is legacy and scares me, so I want to deal with it just once. Is the approach here for each method to have a corresponding C# method? In fact, is there another way of doing this?
Can I have some sort of wrapper subsystem. How do you people generally do this?
Also, are there any performance considerations, etc.?
|
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 the unmanaged (C++ functions). A good place to start is the Platform Invoke Tutorial.
As far as performance considerations go, there typically won't be much to worry about. Calling from C# might be fractionally slower than calling directly from C++, in large part due to marshaling data. Unless the code you're calling is in a critical loop, you're not going to notice any difference.
It really depends on what those native functions do. The more you have to share data between the unmanaged and managed worlds, the more difficult the process becomes. Without more information about your specific functions, it's difficult to say where you might encounter problems.
|
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;
set x = 0;
Some languages require that you assign a value to a variable upon declaration. This requirement allows the compiler or interpreter of the language to infer a type for the variable:
Python
x = 0
|
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 = _capacity * 2;
// copy construct items (copy over from old location).
for(size_type i=0; i<_size; i++)
alloc.construct(_begin1 + i, *(_begin + i));
alloc.construct(_begin1 + _size, t);
// destruct old ones. dtors are not allowed to throw here.
// if they do, behavior is undefined (17.4.3.6/2)
for(size_type i=0;i<_size; i++)
alloc.destroy(_begin + i);
alloc.deallocate(_begin, _capacity);
// set new stuff, after everything worked out nicely
_begin = _begin1;
_capacity = _capacity1;
} else { // size less than capacity
// tell the allocator to allocate an object at the right
// memory place previously allocated
alloc.construct(_begin + _size, t);
}
_size++; // now, we have one more item in us
...
Something like that. The allocator will care about allocating memory. It keeps the steps of allocating memory and constructing object into that memory apart, so it can preallocate memory, but not yet call constructors. During reallocate, the vector has to take care about exceptions being thrown by copy constructors, which complicates the matter somewhat. The above is just some pseudo code snippet - not real code and probably contains many bugs. If the size gets above the capacity, it asks the allocator to allocate a new greater block of memory, if not then it just constructs at the previously allocated space.
The exact semantics of this depend on the allocator. If it is the standard allocator, construct will do
new ((void*)(_start + n)) T(t); // known as "placement new"
And the allocate allocate will just get memory from ::operator new. destroy would call the destructor
(_start + n)->~T();
All that is abstracted behind the allocator and the vector just uses it. A stack or pooling allocator could work completely different. Some key points about vector that are important
After a call to reserve(N), you can have up to N items inserted into your vector without risking a reallocation. Until then, that is as long as size() <= capacity(), references and iterators to elements of it remain valid.
Vector's storage is contiguous. You can treat &v[0] as a buffer containing as many elements you have currently in your vector.
|
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 << std::endl;
}
};
As annotated in the code, I'd like to be able to call the base class's function that I'm overriding. In Java there's the super.funcname() syntax. Is this possible in C++?
|
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++ syntax is like this:
class Bar : public Foo {
// ...
void printStuff() override { // help the compiler to check
Foo::printStuff(); // calls base class' function
}
};
|
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); in repeating cycles
}
TEST( bar ) {
Foo one;
Foo two;
// init one & two
// lots of CHECK_CLOSE(one.bar, two.bar, 1e-5); in repeating cycles
}
And use this:
void blah( const Foo& one, const Foo& two ) {
// lots of CHECK_CLOSE(one.bar, two.bar, 1e-5);
}
TEST( foo ) {
Foo one;
Foo two;
// init one & two
blah(one, two);
}
TEST( bar ) {
Foo one;
Foo two;
// init one & two
blah(one, two);
}
This doesn't work due to UnitTest++'s macro manipulations. What is the best way to approach this problem?
edit: A couple of thoughts which I can't check out right now.
If I use a fixture, with the utility function in the struct, will I be able to call UnitTest++ macros from within this function?
I can write a macro to perform the common tests. I don't really like this, but at least I'll stary dry...
|
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 fairly straightforward to use directly, but it requires declaring lots of little throwaway functions or functor objects, which I'd like to avoid if possible. I've been looking at Boost's lambda library for possible ways to do away with these, but I think I'm missing something fundamental; I just can't get it to do what I want.
One case that's stumped me at the moment: I have a std::vector collection called data; the condition that I'm after is when the size() of that collection reaches a certain threshold. Essentially, then, I want my condition functor to return true when data.size() >= threshold and false otherwise. But I've been having trouble expressing that in lambda syntax.
The best that I've been able to come up with thus far (which at least compiles, though it doesn't work) is this:
boost::function<bool (size_t)> ge = boost::bind(std::greater_equal<size_t>(),
_1, threshold);
boost::function<size_t ()> size = boost::bind(&std::vector<std::string>::size,
data);
DoSomething(boost::lambda::bind(ge, boost::lambda::bind(size)), other stuff);
On entry to DoSomething, the size is 0 -- and even though the size increases during the course of running, the calls to condition() always seem to get a size of 0. Tracing it through (which is a bit tricky through Boost's internals), while it does appear to be calling greater_equal each time condition() is evaluated, it doesn't appear to be calling size().
So what fundamental thing have I completely messed up? Is there a simpler way of expressing this sort of thing (while still keeping the code as inline as possible)?
I'd ideally like to get it as close as possible to the C# equivalent code fluency:
DoSomething(delegate() { return data.size() >= threshold; }, other stuff);
DoSomething(() => (data.size() >= threshold), other stuff);
|
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<std::string>::size,
boost::ref(data));
You can also use the normal >= operator instead of std::greater_equal<> in the definition of your lambda function and combine it all together:
boost::function<bool ()> cond =
(boost::bind(&std::vector<std::string>::size, boost::ref(data))
>= threshold);
DoSomething(cond, other stuff);
|
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 complied program which links to avcodec I get the
following error: "Compiler did not align stack variables. Libavcodec has
been miscompiled", followed by a crash in avcodec.dll.
avcodec.dll was not compiled with msvc, so I'm unable to see what is going on inside.
When running ffmpeg.exe and using the same avcodec.dll everything works well.
ffmpeg.exe was not compiled with msvc, it was complied with gcc / mingw (same as avcodec.dll)
Thanks,
Dan
|
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 introduced. Each word was 2 bytes. And each clock cycle 16 bits of information could be processed. But this posed a small problem.
Let's look at a memory map:
+----+
|0000|
|0001|
+----+
|0002|
|0003|
+----+
|0004|
|0005|
+----+
| .. |
At each address there is a byte which can be accessed individually.
But words can only be fetched at even addresses. So if we read a word at 0000, we read the bytes at 0000 and 0001. But if we want to read the word at position 0001, we need two read accesses. First 0000,0001 and then 0002,0003 and we only keep 0001,0002.
Of course this took some extra time and that was not appreciated. So that's why they invented alignment. So we store word variables at word boundaries and byte variables at byte boundaries.
For example, if we have a structure with a byte field (B) and a word field (W) (and a very naive compiler), we get the following:
+----+
|0000| B
|0001| W
+----+
|0002| W
|0003|
+----+
Which is not fun. But when using word alignment we find:
+----+
|0000| B
|0001| -
+----+
|0002| W
|0003| W
+----+
Here memory is sacrificed for access speed.
You can imagine that when using double word (4 bytes) or quad word (8 bytes) this is even more important. That's why with most modern compilers you can chose which alignment you are using while compiling the program.
|
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 singleton pointer, remove both ##s from your macro.
|
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 MyClass::setFoo(const int foo) { m_foo = foo; } // Removed '&'
Passing a reference to a primitive type should require the same (or more) effort as passing the type's value itself, right?
It's just a number after all...
Is this just some attempted micro-optimization or is there a true benefit?
|
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 choice, and it's very dangerous to return a reference (const or not), in case a variable that gets freed from scope is returned. So if you return a reference, be careful to be sure it is not a variable that goes out of scope.
There is a slight difference for the modifier too, but again probably not something that is worth doing or that was intended.
void test1(int x)
{
cout<<x<<endl;//prints 1
}
void test2(const int &x)
{
cout<<x<<endl;//prints 1 or something else possibly, another thread could have changed x
}
int main(int argc, char**argv)
{
int x = 1;
test1(x);
//...
test2(x);
return 0;
}
So the end result is that you obtain changes even after the parameters are passed.
|
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<multimap<std::string,std::string>::iterator> >
can i somehow avoid this creation of the temp multimap.
Thanks
|
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, multimap<std::string,std::string>::iterator> where first is the iterator and second is the end-iterator.
a pair<multimap<std::string,std::string>::iterator, multimap<std::string,std::string>*> where first is the iterator, and second is a pointer to the multimap that the iterator belongs to.
some other kind of solution.
EDIT: I concur with Mykola Golubyev: It is often a bad idea to store iterators for a longer period of time, as the iterators may be invalidated.
|
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 with LVS_OWNERDATA flag? And when I have to read another one group of rows? Do I need a Prev, Next buttons like if it was a web page grid?
Can you please give me some advice?
Best Regards
P.S. But there is another problem that I have ... CListView is in the main UI thread, but I can request rows only from the second thread which may not always be available for using.
May be I have to block UI thread in callback for rows information?
And is there a way that I can block ListView for asking for a new rows information? May be disable it until my second thread is busy?
|
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)
s->a = new_value;
else
s->b = new_value;
}
For reasons I won't write here I cannot pass the pointer to a/b to f. So I cannot call f with address of my_struct::a or my_struct::b.
Another thing I cannot do is to declare a vector (int vars[2]) within my_struct and pass an integer as index to f. Basically in f I need to access the variables by name.
Problem with previous example is that in the future I plan to add more variables to struct and in that case I shall remember to add more if statements to f, which is bad for portability.
A thing I could do is write f as a macro, like this:
#define FUNC(which)
void f(my_struct* s, int new_value) \
{ \
s->which = new_value; \
}
and then I could call FUNC(a) or FUNC(b).
This would work but I don't like using macros.
So my question is: Is there a way to achieve the same goal using templates instead of macros?
EDIT: I'll try to explain why I cannot use pointers and I need access to variable by name.
Basically the structure contains the state of a system. This systems needs to "undo" its state when requested. Undo is handled using an interface called undo_token like this:
class undo_token
{
public:
void undo(my_struct* s) = 0;
};
So I cannot pass pointers to the undo method because of polymorphism (mystruct contains variables of other types as well).
When I add a new variable to the structure I generally also add a new class, like this:
class undo_a : public undo_token
{
int new_value;
public:
undo_a(int new_value) { this->new_value = new_value; }
void undo(my_struct *s) { s->a = new_value}
};
Problem is I don't know pointer to s when I create the token, so I cannot save a pointer to s::a in the constructor (which would have solved the problem).
The class for "b" is the same, just I have to write "s->b" instead of s->a
Maybe this is a design problem: I need an undo token per variable type, not one per variable...
|
#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>
class undo_member : public undo_token
{
TValue new_value_;
typedef TValue my_struct::* TMember;
TMember member_;
public:
undo_member(TMember member, TValue new_value):
new_value_( new_value ),
member_( member )
{}
void undo(my_struct *s)
{
set( s, member_, new_value_ );
}
};
int main()
{
my_struct s;
set( &s, &my_struct::a, 2 );
set( &s, &my_struct::b, "hello" );
std::cout << "s.a = " << s.a << std::endl;
std::cout << "s.b = " << s.b << std::endl;
undo_member<int> um1( &my_struct::a, 4 );
um1.undo( &s );
std::cout << "s.a = " << s.a << std::endl;
undo_member<std::string> um2( &my_struct::b, "goodbye" );
um2.undo( &s );
std::cout << "s.b = " << s.b << std::endl;
return 0;
}
|
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 explorer directly using the above statement but I cannot directly open one of its folders.
This link explains how to open a IShellFolder
http://msdn.microsoft.com/en-us/library/bb776817(VS.85).aspx#
but I am not sure how to use the objectname param
%SystemRoot%\Explorer.exe /e,::{MyExtension CLSID},objectname
|
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 mind X and Y may inheriting from something, but Dispatcher should allow further clients (not only X and Y).
And I would like to avoid void* pointers if possible :)
|
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 treats it as char. If I have:
unsigned char a = 0;
unsigned char b = 0xff;
cout << "a is " << hex << a <<"; b is " << hex << b << endl;
then the output is:
a is ^@; b is 377
instead of
a is 0; b is ff
I tried using uint8_t, but as I mentioned before, that's typedef'ed to unsigned char, so it does the same. How can I print my variables correctly?
Edit: I do this in many places throughout my code. Is there any way I can do this without casting to int each time I want to print?
|
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 HexCharStruct(_c);
}
int main()
{
char a = 131;
std::cout << hex(a) << std::endl;
}
It's short to write, has the same efficiency as the original solution and it lets you choose to use the "original" character output. And it's type-safe (not using "evil" macros :-))
|
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 MyHashingSolution {
void UpdateHash(int idx, int val) {
...
}
void RecalcHash() {
...
UpdateHash(idx, GetState(idx)); // Problem: no acces to GetState function, can't do recursive application of templates
...
}
};
In this example I can pass MyHashingSolution to State class so State have access to HashingSolution's methods, but HashingSolution can't call GetState. Is it possible to work around this?
This is in the deepest loop. virtual function here drops the performance by more than 25%.
Inlineing is crucial for me.
|
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) {
...
}
void RecalcHash() {
...
UpdateHash(idx, derived().GetState(idx));
...
}
private:
// Just for convenience
Derived& derived() { return *static_cast<Derived*>(this); }
};
In this case, because you want the derived State class to also be a template, you need to take the slightly unusual step of declaring State as a class template that takes a template template parameter:
template <template <class T> class HashingSolution>
struct State : public HashingSolution<State<HashingSolution> > {
typedef HashingSolution<State<HashingSolution> > Parent;
void Update(int idx, int val) {
Parent::UpdateHash(idx, val); // g++ requires "Parent::"
}
int GetState(int idx) {
return ...;
}
};
The key point is that, provided State inherits from HashingSolution<State<HashingSolution> >, Derived is a derived class of HashingSolution<State<HashingSolution> > so the static_cast<Derived*>(this) downcast in HashingSolution<State>::derived() compiles and works correctly. (If you mess up and derive State from HashingSolution<SomeOtherType> instead and then try something that involves a call to derived(), the compiler will complain as the requirements for static_cast<> are not met.)
Then declare the concrete State class you want to use like so:
typedef State<MyHashingSolution> MyState;
Unfortunately this solution has the side effect that you will need to change DummyHashingSolution (and any other such types) to templates that ignore their one template argument, in order to make them usable as template template arguments.
|
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 classes or namespaces.
C-x 3
This gives you a display with two buffers side-by side. You can then proceed to load different files in them, and move your cursor from one to the other with C-x o. This is pretty basic stuff, but I mention it because of how powerful it makes the next one...
C-x (
(type any amount of stuff and/or emacs commands here)
C-x )
This is how you define a macro in emacs. Any time you find yourself needing to do the same thing over and over to a bunch of code (and it is too complex for query-replace), this is a lifesaver. If you mess up, you can hit C-g to stop the macro definition, and then undo (C-_) until you are back to where you started. The keys to invoke the macro are C-x e. If you want to do it a bunch of times, you can hit Esc and type in a number first. Eg: Esc 100 C-x e will try to invoke your macro 100 times.
(Note: On Windows you can get "Meta" by hitting the Esc key, or holding down Alt).
|
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 from the project. "Engine" in this example would be the master class calling the update_all.
class Logic
{
public:
Logic() { all.push_back(this); }
virtual ~Logic() { all.erase(this); }
virtual void update(float deltatime) = 0;
private:
friend Engine;
static std::list<Logic*> all;
static void update_all(float deltatime)
{
for (std::list::iterator i = all.begin(); i!=all.end(); ++i)
(*i)->update(deltatime);
}
};
Does this pattern have a name?
Do you consider this a nicer approach than a singleton manager class?
Any other comments or caveats?
|
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 siukurnin mentioned (deletion of a Logic object during update()). list::remove() doesn't invalidate iterators except of the ones pointing to the removed element.
Apart from this, I also vote for this being a variation of the singleton pattern. And I would suggest for keeping the original solution with a separate management class, just in case you want to have to have two loops with different delta times or explicit multithread support (different Logic objects on different threads) or whatever in the future.
In my opinion this is a general advantage of the singleton class over static methods (which you could always use): You can easily multiply your functionality if you want to do so in the future ...
|
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 that tried to do this from an odd/unalighed memory location
((uint16 *)pBuffer)[index] = value;
where value is of type uint16 and index is bounds checked and indexes pBuffer. This causes a unaligned memory access exception. pBuffer points to char * on the heap.
As mentioned, even though we can peek into the third-party stack, we can not update the code officially. So we notify the provider and they provide the update in the next release.
I want to understand if there is a work around for this. How do I perform the above assignment without violating the unaligned access? What is the best approach to resolving such problems.
|
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 managed classes.
Is there some flag somewhere I need to set? Or do I have to do some DllImport magic?
This is on .NET 2.0 and Visual Studio 2005.
|
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)] short int wDayOfWeek;
[FieldOffset(6)] short int wDay;
[FieldOffset(8)] short int wHour;
[FieldOffset(10)] short int wMinute;
[FieldOffset(12)] short int wSecond;
[FieldOffset(14)] short int wMilliseconds;
};
Am I imagining this, or are the elements in square brackets not consistent with C++ syntax?
Why go through the trouble of doing all of this when C++ provides adequate tools to specify struct layout within the standard definition of the language (and perhaps with the typically supported #pragma pack() ). Doesn't the compatibility designed into the language guarantee that you can define in C++ any struct you can define in C? I understand the need to be able to explicitly describe the layout of a C struct in other languages, but it seems like it would not be necessary with C++ which provides
extern "C" { }
|
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 control that, you need special pragmas to control "packing". These are platform specific. So what you're seeing here is just the CLR equivalent of that.
Update: that example is from the documentation for an older version of Microsoft's CLI integration for C++, which was called Managed C++. It was abandoned very quickly and replaced in the next version by C++/CLI - a grafting of CLI features into C++ that is so complete and wide-ranging, it effectively becomes a different language just as C++ is a different language from C.
|
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 that prints the prompt.
Now in Python I would solve that problem by catching EOFError, but in C++ no exception is raised I could catch and there doesn't seem to be a setting on cin to ignore EOF.
Any hints?
|
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 using _tcstod instead, but that takes an extra parameter that i'm not very interested in. So any ideas why there is no _ttof, _tcstof() or _wtof in Windows Mobile 5.0. It's there in VS2005. Am I missing something really obvious here?
|
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::b[0]);
However, the compiler just complains about an "invalid use of non-static data member 'foo::b'"
Is it possible to do this at all (or at least without unions)?
Edit: I need a pointer to a specific element of an array, so int foo::* ptr points to the second element of the array (foo::b[1]).
Yet another edit: I need to access the element in the array by bar.*ptr=2, as the pointer gets used somewhere else, so it can't be called with bar.*ptr[1]=2 or *ptr=2.
|
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 can't do this either!
bar.a=1;
std::cout << bar.*aptr << std::endl;
}
What you can do is define member functions that return the int you want:
struct foo
{
int a;
int *b;
int c[2];
int &GetA() { return a; } // changed to return references so you can modify the values
int &Getb() { return *b; }
template <int index>
int &GetC() { return c[index]; }
};
typedef long &(Test::*IntAccessor)();
void SetValue(foo &f, IntAccessor ptr, int newValue)
{
cout << "Value before: " << f.*ptr();
f.*ptr() = newValue;
cout << "Value after: " << f.*ptr();
}
int main()
{
IntAccessor aptr=&foo::GetA;
IntAccessor bptr=&foo::GetB;
IntAccessor cptr=&foo::GetC<1>;
int local;
foo bar;
bar.a=1;
bar.b = &local;
bar.c[1] = 2;
SetValue(bar, aptr, 2);
SetValue(bar, bptr, 3);
SetValue(bar, cptr, 4);
SetValue(bar, &foo::GetC<0>, 5);
}
Then you at least have a consistent interface to allow you to change different values for foo.
|
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 can make any changes/additions to it that I need to.
A third party application is going to load my DLL on startup and expects the DLLExport to be defined a certain way, so i can't really change the method signature thats getting exported.
The C# app I'm building is going to be used as a wrapper so i can integrate this C++ piece into some of our other applications, which are all written in C#.
The C++ method signature I need to call looks like this
DllExport int Calculate (const MathInputStuctType *input,
MathOutputStructType *output, void **formulaStorage)
And MathInputStructType is defined as the following
typedef struct MathInputStuctTypeS {
int _setData;
double _data[(int) FieldSize];
int _setTdData;
} MathInputStuctType;
|
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 people might have.
Note: a corner-stitched data structure is a way to store 2 dimensional, rectangluar data, explicitly maintaining the whitespace between inserted elements. This is as opposed to a quad-tree which just stores the inserted data elements. There are many trade-offs, I'm mostly interested in an implementation - but would also accept alternatives that have similar properties.
|
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 "robust". However, if there is any performance hit then I will probably not use C++ style casts and will instead spend more time testing the code that uses C-style casts.
Has anyone done any rigorous testing/profiling to compare the performance of C++ style casts to C style casts?
What were your results?
What conclusions did you draw?
|
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);
generates identical code for both casts with VC++ - code is:
00401041 fld dword ptr [ebp-8]
00401044 call __ftol (0040110c)
00401049 mov dword ptr [ebp-4],eax
The only C++ cast that can throw is dynamic_cast when casting to a reference. To avoid this, cast to a pointer, which will return 0 if the cast fails.
|
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 method calls
void doSomething(Pair<Integer, Integer> id) {
Integer productId = id.first();
Integer quantity = id.second();
}
Instead of
class ProductsOrdered {
int productId;
int quantityOrdered;
// accessor methods, etc
}
List<ProductsOrderded> productsOrdered = blah();
Many other uses of the Pair in the codebase are similarly bad-smelling.
I Googled tuples and they seem to be often misunderstood or used in dubious ways. Is there a convincing argument for or against their use? I can appreciate not wanting to create huge class hierarchies but are there realistic codebases where the class hierarchy would explode if tuples weren't used?
|
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 kind of wrapper class with accessor methods for every permutation of two types.
Finally, they're useful for returning multiple values. There's really no reason to make a class specifically for a function's multiple return values, and they shouldn't be treated as one object if they're unrelated.
To be fair, the code you pasted is a bad use of a pair.
|
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 possible combination, e.g. "Parallel with Python", "Parallel without Python", etc. There are just too many combinations. Is this a situation where I could use MSBuild?
Edit: One possibility I considered is to create a bunch of .vsprops files, but this is essentially the same as creating a bunch of different configurations.
Edit: Maybe CMake is more what I'm looking for? I'd love to hear from any CMake users out there...
|
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 appears.
Unfortunate, but one rarely wins in a fight against Visual Studio, so I personally have always given in and created as many configurations as needed. It's a pain, and it's fiddly, and yes the IDE should ideally provide some better mechanism for managing the combinations -- but it's doable, just about, and it doesn't actually take as long to set up as it feels like at the time.
(As I understand them, .vsprops can take some of the pain away by allowing easy sharing of configuration settings between configurations. So those miniscule text boxes in VS are only used to set up the settings that differ between configurations. This may make them still worth investigating. This isn't something I've used myself yet, though; only discovered it recently.)
|
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 particular object is derived from the ref-count object, but a common function to get an instance of these objects (GetExisting) hides an AddRef() within itself without advertising that it is doing so. This necessitates doing a Release at the end of the functional block to free the hidden ref, but a developer who didn't inspect the implementation of GetExisting() wouldn't know that, and someone who forgets to add a Release at the end of the function (say, during a mad dash of bug-fixing crunch time) leaks objects. This, of course, was my burn.
void SomeFunction(ProgramStateInfo *P)
{
ThreadClass *thread = ThreadClass::GetExisting( P );
// some code goes here
bool result = UseThreadSomehow(thread);
// some code goes here
thread->Release(); // Need to do this because GetExisting() calls AddRef()
}
So I wrote up a little class to avoid the need for the Release() at the end of these functions.
class ThreadContainer
{
private:
ThreadClass *m_T;
public:
ThreadContainer(Thread *T){ m_T = T; }
~ThreadContainer() { if(m_T) m_T->Release(); }
ThreadClass * Thread() const { return m_T; }
};
So that now I can just do this:
void SomeFunction(ProgramStateInfo *P)
{
ThreadContainer ThreadC(ThreadClass::GetExisting( P ));
// some code goes here
bool result = UseThreadSomehow(ThreadC.Thread());
// some code goes here
// Automagic Release() in ThreadC Destructor!!!
}
What I don't like is that to access the thread pointer, I have to call a member function of ThreadContainer, Thread(). Is there some clever way that I can clean that up so that it's syntactically prettier, or would anything like that obscure the meaning of the container and introduce new problems for developers unfamiliar with the code?
Thanks.
|
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... */
io_service.run();
}
};
socket.cpp:
using boost::asio::ip::tcp;
bool some_class::connect(char* host, char* port)
{
printf("Resolving hostname...\n");
/* Resolve hostname. */
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), host, port);
tcp::resolver::iterator iterator = resolver.resolve(query);
printf("Connecting to %s:%s... ", host, port);
/* Connect to resolved hosts. */
sock->connect(*iterator);
return true;
}
g++ builds this without any errors, but the code never makes it past the resolver.resolve() call.
I've tried both "127.0.0.1" and "localhost" for host and "80" for port. (don't think it should matter, but apache2 is up and running)
When I ctrl+c out of my application, it obviously terminates but it does output the "Connecting to string" just before it does.
I am planning on building the example myself and seeing if the same problem occurs, and will definitely post the results here. Has anyone encountered this issue or knows what could possibly cause this behavior?
edit:
The example runs just fine... I have some debugging to do I suppose.
second edit:
I don't get it, the only thing that could be different is host/port.
Example uses char* argv[] and I'm using:
char host[] = "localhost";
char port[] = "80";
third edit:
it indeed seems to be blocking at connect, forgot to fflush(stdout). then it has to be a problem with the socket. going to do some more testing.
fourth edit:
stupid me, it wasn't blocking at all! I was just relying too much on console output..
|
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 you're going to push a vector of things, but don't worry about that until it's working (and then only if it becomes a problem).
|
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 storing my vertices like vector<Point> poly. You can assume Point is just a basic struct with two doubles x and y, with points indexed sequentially in CCW order.
If i < j, then I just need to copy the vertices from i to j (inclusive) into one vector, and then from j to n-1 plus 0 to i into another. Or vice versa for the other case, right?
Here's the code I'm using, but it doesn't seem to work right (let j == closestIndex):
if (i < closestIndex) {
lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + closestIndex + 1);
upperPoly.insert(upperPoly.end(), poly.begin() + closestIndex, poly.end());
upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
} else {
lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end());
lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + closestIndex + 1);
upperPoly.insert(upperPoly.end(), poly.begin() + closestIndex, poly.begin() + i + 1);
}
|
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 to closestIndex
lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + closestIndex + 1);
upperPoly.insert(upperPoly.end(), poly.begin() + closestIndex, poly.end());
upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
|
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 access them. I understand that this is because there is only a finite amount of memory on the stack, as opposed to the heap which has more memory.
I have tried the following without much luck (does not compile):
#define SIZE 262144
int *myArray[SIZE] = new int[SIZE];
And then I considered using malloc, but I was wondering if there was a more C++ like way of doing this...
#define SIZE 262144
int *myArray = (int*)malloc(sizeof(int) * SIZE);
Should I just go with malloc?
|
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'll need to delete it, and since its an array, you should use:
delete [] myArray;
|
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 compile in MSVC with full optimizations, the output I get is "-1?". If I compile in Debug mode (no optimizations), I get no output (expected.)
I thought the standard guaranteed that unsigned integers overflowed in a predictable way, so that when i = (unsigned int)(-1), i+1 = 0, and the loop condition i + 1 >= 1 fails. Instead, the test is somehow passing. Is this a compiler bug, or am I doing something undefined somewhere?
|
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 newsgroup discussion here.
|
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 devices).
Is there a flag or something I can pass to SDL so that it does not capture SIGINT? I really just want the program to stop when it receives the signal (ie when I press ctrl-c).
|
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 fail because the memory c points to has already been freed.
You need a copy constructor.
To see whats happening, put some couts in the constructors and destructors and step through the code.
|
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%
The application is written in C++.
Does the frequent call to free() will lead to performance issues?
Promoted from a comment by the OP: the parser being used in expat, which is a SAX parser with a very small footprint, and customisable memory management.
|
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 information. The call method instruction may sometimes be slower in C++, as the C# JIT may be able to use a quicker instruction that only copes with a small offset as it know more about the runtime memory layout and processor model then a C++ compiler.
However we are talking about a handful of processor instruction at most here. On a modem superscalar processor, it is very possible that the “null check” instruct is run at the same time as the “call method” and therefore takes no time.
It is also very likely that all the processor instructions will already in be the level 1 cache if the call is make in a loop. But the data is less likely to be caches, the cost of reading a data value from main memory these days is the same as running 100s of instructions from the level 1 cache. Therefore it is unlucky that in real applications the cost of a virtual call is even measurable in more then a very few places.
The fact that the C# code uses a few more instructions will of course reduce the amount of code that can fit in the cache, the effect of this is impossible to predict.
(If the C++ class uses multiple inherence then the cost is more, due to having to patch up the “this” pointer. Likewise interfaces in C# add another level of redirection.)
|
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 different approaches with a lot of different APIs and the whole topic confuses me a little.
Can anyone point me to some resources or tell me where to start?
Thanks!
|
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 any change.
I did have the dlls in C:\WINDOWS\WinSxS\x86_Microsoft.VC80.DebugCRT_1fc8b3b9a1e18e3b_8.0.50727.42_x-ww_f75eb16c.
I opened the \debug\.exe.intermediate.manifest file and it had 2 (dependentAssembly) entries:
1st: name='Microsoft.VC80.DebugCRT' version='8.0.50608.0'
2nd: name='Microsoft.VC80.DebugCRT' version='8.0.50727.762'
If I delete one and change the other one to
name='Microsoft.VC80.DebugCRT' version='8.0.50727.42'
I can get a build that will start.
Granted I did have VS2008 installed - but what is controlling the versions ? or How can I get the right debug dll version to "stick".
VS2008 was de-installed through the control panel.
EDIT: Found nothing in the registry if DebugCRT is searched for.
the environment path points to the VS8 folders .
There is only 1 DebugCRT folder in the c:\windows\winsxs\policies folder
(8.0.50.727.42)
The c:\windows\winsxs\manifests folder only has the .42 version of .cat and .manifest
The .manifest file (in above manifest folder) has version="8.0.50727.42"
Clarification: the manifest file has 2 "dependentAssembly" entries each with different versions and not the .42. I can delete 1 entry and change the version on the other to match the .42 to get a debug build that starts.
EDIT2:I'm also using boost and inside the DLLs there is the .762 version
|
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 solution for version used.
|
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 doSomething(B *b))
|
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. Isn't a segmentation fault when you have a null reference? If so, how can an empty method have a null reference?
This piece of code, seems to be causing the issue:
#include <sys/socket.h>
#define BUFFER_SIZE 256
char *buffer;
buffer = (char*)GetSomePointer()->SomeStackMemoryString.c_str();
int writeResult = write(socketFD, buffer, BUFFER_SIZE);
bzero(buffer, BUFFER_SIZE);
int readResult = read(socketFD, buffer, BUFFER_SIZE);
When the line using the read(...) method is commented out, the problem goes away.
Update:
I have changed the question to point toward the actual problem, and I have removed all the irrelevant code - and I also answered my own question so that people reading this know specifically what the issue is, please read my answer before saying "you're a moron!".
|
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 allocated (and zeroed out).
|
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->MyBaseClass::~MyBaseClass();
// Some destructing specific to MyChildClass
}
Am I right?
|
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 the answers, I take that (please edit if incorrect):
delete of an instance of B calls B::~B();
which calls A::~A();
A::~A should explicitly delete all heap-allocated member variables of the A object;
Finally the memory block storing said instance of class B is returned to the heap - when new was used, it first allocated a block of memory on heap, then invoked constructors to initialize it, now after all destructors have been invoked to finalize the object the block where the object resided is returned to the heap.
|
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, but a full member), then this will happen when the containing object is destroyed.
class A
{
char *someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { delete[] someHeapMemory; }
};
class B
{
A* APtr;
public:
B() : APtr(new A()) {}
~B() { delete APtr; }
};
class C
{
A Amember;
public:
C() : Amember() {}
~C() {} // A is freed / destructed automatically.
};
int main()
{
B* BPtr = new B();
delete BPtr; // Calls ~B() which calls ~A()
C *CPtr = new C();
delete CPtr;
B b;
C c;
} // b and c are freed/destructed automatically
In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.
auto_ptr, unique_ptr and shared_ptr etc... are great for making this lifetime management much easier:
class A
{
shared_array<char> someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { } // someHeapMemory is delete[]d automatically
};
class B
{
shared_ptr<A> APtr;
public:
B() : APtr(new A()) {}
~B() { } // APtr is deleted automatically
};
int main()
{
shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically
|
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 way to get the PID of the parent of a given process, so as to get, from my MFC app, the root IE PID.
Sysinternals' ProcessExplorer knows how to do that, displaying processes in treeview, so I'm sure there's a way to achieve that.
|
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 situation where the memory is automatically deallocated on exit?
For example, is there any point in doing this?
int main(...)
{
A* a = new A();
a->DoSomething();
delete a;
return 0;
}
I was thinking maybe in case I refactor (or someone else refactors) that code and puts it elsewhere in the application, where delete is really necessary.
As well as the answer by Brian R. Bondy (which talks specifically about the implications in C++), Paul Tomblin also has a good answer to a C specific question, which also talks about the C++ destructor.
|
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 program ends. But it is good practice to deallocate it yourself and like I said above the OS won't call your destructor.
As for calling delete in general, yes you always want to call delete, or else you will have a memory leak in your program, which will lead to new allocations failing.
|
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 the elements equal to Bad?
Thanks
PS
struct CMyClass {
void *Ptr;
int Var;
}
bool is_equal(const CMyClass &A, const CMyClass &B)
{
if (A.Ptr == B.Prt and A.Var == B.Var)
return true;
else
return false;
}
|
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 to use remove_if.
In the following example list::remove and list::remove_if is demonstrated.
struct Class
{
int a_;
int b_;
Class( int a, int b ):
a_( a ),
b_( b )
{}
bool operator == (const Class &rhs)
{
return (rhs.a_ == a_ && rhs.b_ == b_);
}
void print()
{
std::cout << a_ << " " << b_ << std::endl;
}
};
bool isEqual( Class lhs, Class rhs )
{
return (rhs.a_ == lhs.a_ && rhs.b_ == lhs.b_);
}
struct IsEqual
{
IsEqual( const Class& value ):
value_( value )
{}
bool operator() (const Class &rhs)
{
return (rhs.a_ == value_.a_ && rhs.b_ == value_.b_);
}
Class value_;
};
int main()
{
std::list<Class> l;
l.push_back( Class( 1, 3 ) );
l.push_back( Class( 2, 5 ) );
l.push_back( Class( 3, 5 ) );
l.push_back( Class( 3, 8 ) );
Class bad( 2, 5 );
std::cout << "operator == " << std::endl;
l.remove( bad );
std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );
std::cout << "binary function predicat" << std::endl;
l.push_back( Class( 2, 5 ) );
l.remove_if( std::bind2nd( std::ptr_fun(isEqual), bad ) );
std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );
std::cout << "functor predicat" << std::endl;
l.push_back( Class( 2, 5 ) );
l.remove_if( IsEqual( bad ) );
std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );
return 0;
}
|
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 getting into platform-specific filesystem details (links, etc).
If you want something higher-level, more robust, and more portable, check out Boost Filesystem.
|
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 those values seems to work. The first client connects as expected, but any subsequent clients just block while the first client finishes. What's really confusing to me is that they don't block on connecting to the server, they block on the first read.
I used the code here to get started writing my client and server. Does anyone know what I need to change to get the server to accept only one client connection, and drop any subsequent connection attempts?
|
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 difference that you are looking for compared to closing the new accepted socket right after the accept? The client will know as soon as it tries to use its socket (or right away if it is already waiting on the server with a read call) with a last error of: server actively closed the connection.
|
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 plenty of guides/tutorials around on their forum/wiki. The documentation is also very good.
It's well worth checking out.
Hrmm, upon reading that it almost sounds like I have a vested interest - I don't! I just really like it from past experience!
|
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 debugger jumps to the line containing the ASSERT call (as opposed to the disassembly somewhere like some other ASSERT functions). So it's all pretty much working.
But what would be really cool would be to display the name of the function that failed.
Then I can decide whether to debug it without trying to guess what function it's in from the filename.
e.g. if I have the following function:
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
ASSERT(lpCreateStruct->cx > 0);
...
}
Then when the ASSERT fires, the messagebox would show something like:
Function = CMainFrame::OnCreate
So, what's the simplest way of finding out the current function name, at runtime?
It should not use MFC or the .NET framework, even though I do use both of these.
It should be as portable as possible.
|
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__
int foo()
{
int a = 0;
THROW_IF(a > 0); // will throw "error in foo()"
}
|
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:
vertexbuffers.cpp(31) : error C3861: 'glGenBuffers': identifier not found
vertexbuffers.cpp(32) : error C2065: 'GL_ARRAY_BUFFER' : undeclared identifier
vertexbuffers.cpp(32) : error C3861: 'glBindBuffer': identifier not found
vertexbuffers.cpp(33) : error C2065: 'GL_ARRAY_BUFFER' : undeclared identifier
vertexbuffers.cpp(33) : error C2065: 'GL_STATIC_DRAW' : undeclared identifier
vertexbuffers.cpp(33) : error C3861: 'glBufferData': identifier not found
When I examined <GL\gl.h> (contained in C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\gl), I saw:
/* ClientArrayType */
/* GL_VERTEX_ARRAY */
/* GL_NORMAL_ARRAY */
/* GL_COLOR_ARRAY */
Update but it would seem that those contants get defined elsewhere.
How am I supposed to generate buffers if I don't have access to those functions?
The documentation doesn't say that those array types are disabled. How do I get access to the real implementation on OpenGL on Windows?
|
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 for glGenBuffers you will see that it is only available in OpenGL 1.5 and higher. The header file for Windows only comes with OpenGL 1.2 and you should use the extension mechanism to access the newer functionality. If you call wglGetProcAddress with the function name, e.g.
void (__stdcall *glGenBuffers)(GLsizei,GLuint*) =
wglGetProcAddress("glGenBuffers");
then you have a pointer to the function.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.