POD global object initialization
Posted
by paercebal
on Stack Overflow
See other posts from Stack Overflow
or by paercebal
Published on 2010-06-02T18:10:22Z
Indexed on
2010/06/02
18:14 UTC
Read the original article
Hit count: 396
I've got bitten today by a bug.
The following source can be copy/pasted (and then compiled) into a main.cpp file
#include <iostream>
// The point of SomeGlobalObject is for its
// constructor to be launched before the main
// ...
struct SomeGlobalObject
{
SomeGlobalObject() ;
} ;
// ...
// Which explains the global object
SomeGlobalObject oSomeGlobalObject ;
// A POD... I was hoping it would be constructed at
// compile time when using an argument list
struct MyPod
{
short m_short ;
const char * const m_string ;
} ;
// declaration/Initialization of a MyPod array
MyPod myArrayOfPod[] =
{ { 1, "Hello" }, { 2, "World" }, { 3, " !" } } ;
// declaration/Initialization of an array of array of void *
void * myArrayOfVoid[][2] =
{ { (void *)1, "Hello" }, { (void *)2, "World" }, { (void *)3, " !" } } ;
// constructor of the global object... Launched BEFORE main
SomeGlobalObject::SomeGlobalObject()
{
std::cout << "myArrayOfPod[0].m_short : " << myArrayOfPod[0].m_short << std::endl ;
std::cout << "myArrayOfVoid[0][0] : " << myArrayOfVoid[0][0] << std::endl ;
}
// main... What else ?
int main(int argc, char* argv[])
{
return 0 ;
}
MyPod being a POD, I believed there would be no constructors. Only initialization at compile time.
Thus, the global object SomeGlobalObject
would have no problem to use the global array of PODs upon its construction.
The problem is that in real life, nothing is so simple. On Visual C++ 2008 (I did not test on other compilers), upon execution myArrayOfPodis not initialized, even if
myArrayOfVoid` is initialized.
So my questions is: Are C++ compilers not supposed to initialize global PODs (including POD structures) at compilation time ?
Note that I know global variable are evil, and I know that one can't be sure of the order of creation of global variables declared in different compilation units. The problem here is really the POD C-like initialization which seems to call a constructor (the default, compiler-generated one?).
And to make everyone happy: This is on debug. On release, the global array of PODs is correctly initialized.
© Stack Overflow or respective owner