I had a strange problem ,
declare a static member variable whose name is B class in A class . And initialize in the cpp file. but the constructor of B class was never called. I try to use some small test , the test constructor could be called normally. so it is very strange for our production system.
The code like this , in hpp:
class Test
{
public:
Test()
{
ofstream file("/tmp/wup.txt",ios::app);
file << "wup in test" << endl;
file.close();
}
};
//## An extended personality
class TsdNAExtPersonality : public TsdNAPersonality{
public:
TsdNAExtPersonality(
s_gg62_personRec * gg62Header,
TsdNAFunctionType requiredFunctionType);
private:
static Test test;
public:
TsdNAExtPersonality( string * personalityFile, TsdNAFunctionType requiredFunctionType);
};
And in another cpp file I initialize with
Test TsdNAExtPersonality::test;
I have tried in several way, but i found all of ways are unusefull.
the environment is HP-UX ,and the compile is aCC
so my question are :
is there any compile option will influence the variable ? in other words, all the static variable will not be initialized.
from the standard of C++ it should be called when the library was load, right?
I put another static int value using the same way, it could be initialized. but the class constructor is not called , very strange.
is there any mistake in my code ?
from the standard of C++ it should be called when the library was load, right?
No. Dynamic initialisation of an object with static storage duration is guaranteed to happen before execution of any function defined in the same translation unit. If there are no such functions, or your program never calls them, then there's no guarantee that it will ever be initialised.
I put another static int value using the same way, it could be initialized. but the class constructor is not called , very strange.
An int
variable is initialised statically, before the program starts, as long as its initialiser is constant.
is there any compile option will influence the variable ?
Not that I know of, but I'm not familiar with your platform. You could give yourself more control over the object's creation by scoping it within a function:
static Test & test() {
static Test test;
return test;
}
Now it is guaranteed to be initialised the first time the function is called. Of course, you'll need to remember to call it at some point.