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.
The static objects are only destroyed when the program terminates i.e. they live until program termination.
Static destructors are executed one by one in reverse order to the order of corresponding classes definition. Static destructors are always executed after software entry point and always after constructors of all global objects.
You can't delete static variable . And if this is a static pointer in that scenario if depends how did you allocated memory to your variable you can use delete etc. But yes smart pointer is the good approach as mentioned in above post you can use auto_ptr etc.
Static variables are the variables which once declared, they get destroyed only when the program has completed its execution. They have a property of retaining their previous scope value if they are already declared once in the program.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With