Static Data Instantiation Template?

Can anyone tell me what is really going on in this code?

#include <iostream> class BBB { public: BBB() { std::cout << std::endl << "BBB()" << std::endl; } ~BBB() { std::cout << std::endl << "~BBB()" << std::endl; } }; template<class T> class AAA { public: AAA(){} ~AAA(){} void foo() {} private: static BBB b; }; template<class T> BBB AAA<T>::b; //class CCC { // //private: // // static BBB bb; // //}; // //BBB CCC::bb; AAA<int> a; int main() { //AAA<int> a; a.foo(); return 0; } 

It seems that the constructor of object "b" in AAA is not called when the contained class is a template. Try to parse the CCC class definition and the constructor of the "bb" object is called. This is strange since an instance of the template class A.

Help is appreciated.

+4
source share
2 answers

In most cases, each member of a class template is created only if this particular element is used. Since your code never uses member AAA<int>::b , this element is not created.

Adding a no-operation b; operator b; in AAA<T>::AAA() or AAA<T>::~AAA() or AAA<T>::foo() calls the static object AAA<int>::b , which will be constructed and destroyed as you expected.

Or, if you want to tell the compiler to implement all instances of a specific specialization of a particular class, use explicit instantiation (in the source file, not in the header):

 template class AAA<int>; 
+4
source

Templates are different from other classes when only what is used is used. Since you never use a UPS inside A, it is never created.

+1
source

Source: https://habr.com/ru/post/1341584/


All Articles