If I take this
in an static object and store it in a vector in a Singleton object, can I assume the pointer points to the object during the whole lifetime of the program?
Asked
Active
Viewed 460 times
7

Rakete1111
- 47,013
- 16
- 123
- 162

user1056903
- 921
- 9
- 26
-
1If you do the singleton this way, http://stackoverflow.com/questions/6993400/managing-a-singleton-destructor/6993501#6993501, then as long as you access the instance from the managing singleton, order of creation and destruction is effectively guaranteed. – Nim Sep 17 '16 at 17:28
1 Answers
2
In general, you can't assume that, because order of static object creation in different translation units is unspecified. In this case it will work, because there is only single 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;
};
A A::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 defined in different translation unit? Will it be created before static Singleton
is created? You can't be sure.

xinaiz
- 7,744
- 6
- 34
- 78