This static object pointer

If I take this in a static object and store it in a vector in a Singleton object, can I assume that the pointer points to the object for the entire lifetime of the program?

+7
c ++ static
source share
1 answer

In general, you cannot assume that, since the order of creating a static object in different translation units is not specified. In this case, it will work, because there is only one translation unit:

 #include <iostream> #include <vector> class A { A() = default; A(int x) : test(x) {} A * const get_this(void) {return this;} static A staticA; public: static A * const get_static_this(void) {return staticA.get_this();} int test; }; AA::staticA(100); class Singleton { Singleton(A * const ptr) {ptrs_.push_back(ptr);} std::vector<A*> ptrs_; public: static Singleton& getSingleton() {static Singleton singleton(A::get_static_this()); return singleton;} void print_vec() {for(auto x : ptrs_) std::cout << x->test << std::endl;} }; int main() { std::cout << "Singleton contains: "; Singleton::getSingleton().print_vec(); return 0; } 

Output:

 Singleton contains: 100 

But what if A::staticA in a definition in a different translation unit? Will it be created before static Singleton ? You cannot be sure.

+2
source share

All Articles