GoodCode
GoodCode

Reputation: 41

Template Class Static Data Instantiation?

Any one can tell me what on earth is 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 "b" object in AAA is not called when the containing class is template. Try uncomment the CCC class definition and the "bb" object constructor will be called. This is strange since the template class A is instantiated.

Help is greatly appreciated.

Upvotes: 4

Views: 301

Answers (2)

aschepler
aschepler

Reputation: 72311

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

Adding the no-operation statement b; to AAA<T>::AAA() or AAA<T>::~AAA() or AAA<T>::foo() causes the AAA<int>::b static object to be constructed and destructed as you expected.

Or, if you want to tell the compiler to go ahead and instantiate all members of a certain class template specialization, use an explicit instantiation (in a source file, not header):

template class AAA<int>;

Upvotes: 4

Edward Strange
Edward Strange

Reputation: 40859

Templates are different than other kinds of classes in that only what is used is ever instantiated. Since you never actually USE the BBB inside of A, it is never created.

Upvotes: 1

Related Questions