I have a piece of simple C++ code, in which I defined a template and a global object by specializing the template. The object constructor accesses a static member in the specialized template. But it turns out the static member is not initialized at that point. But for a local object (defined in the body of a function), it works. I'm confused...
My c++ compiler is: g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
/////////////////////////
template<typename T>
class TB{
public:
const char *_name;
TB(const char * str):_name(str){
cout << "constructor is called:" << _name << endl;
};
virtual ~TB(){
cout << "destructor is called:" << _name << endl;
};
};
template<typename T>
class TA{
public:
const char *_name;
TA(const char * str):_name(str){
cout << "constructor is called:" << _name << endl;
cout << tb._name <<endl;
};
virtual ~TA(){
cout << "destructor is called:" << _name << endl;
};
static TB<T> tb;
};
template<typename T>
TB<T> TA<T>::tb("static-tb");
TA<int> ta("global-ta");
int main(int argc,char ** argv){
cout << "program started." << endl;
cout << "program stopped." << endl;
return 0;
}
/////////////////////////
// OUTPUT:
constructor is called:global-ta
// yes, only such a single line.
If I put the definition of ta in main() like the following, it works.
int main(int argc,char ** argv){
cout << "program started." << endl;
TA<int> ta("local-ta");
cout << "program stopped." << endl;
return 0;
}
/////////////////////
// OUTPUT:
constructor is called:static-tb
program started.
constructor is called:local-ta
static-tb
program stopped.
destructor is called:local-ta
destructor is called:static-tb
// end of output
cout
toprintf
see the output.TB<T> TA<T>::tb("static-tb");
is not instantiated, ref stackoverflow.com/questions/6959665/… – Liu Hao