简体   繁体   中英

Automatic destruction of static object

Why doesn't C++ create/destroy a static member of a template type.

Observe the following example:

#include <iostream>

struct Dump {
  Dump() {
    std::cout << "CTOR" << std::endl;
  }
  ~Dump() {
    std::cout << "DTOR" << std::endl;
  }
};

template <typename T> struct X {
  static Dump dump;
};

template <typename T> Dump X<T>::dump;

struct A : X<A> {
};

int main() {
  A a;
  return 0;
}

I would have expected that on execution I see the string CTOR followed by DTOR . While I don't. What am I missing here?

It has something to do with dump being the member of a template type, but that's as far as I get.

I found something in § 14.7.1 Implicit instantiation .

1/ [...] The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, scoped member enumerations, static data members and member templates. [...]

It goes on in the second note:

2/ Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

Therefore, unless you use it, it should not be instantiated . This is not an optimization, just Standard [n3092] conformance.

It is not instantiated, unless used. This works :

int main()
{
    A a;
    (void) a.dump;
}

Also, fix the compilation error :

template <typename T> Dump X<T>::dump;

Members of class templates are only instantiated if they are needed; in this case, nothing refers to the static member, so it is not instantiated, even if the class template itself is.

You'll find that putting the statement X<A>::dump; somewhere will cause the member to be instantiated and an object created and destroyed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM