一般来说,您不能这样假设,因为不同翻译单元中静态对象创建的顺序是未指定的。在这种情况下它会起作用,因为只有一个翻译单元:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Singleton contains: 100
Run Code Online (Sandbox Code Playgroud)
但是如果A::staticA在不同的翻译单元中定义怎么办?会在static Singleton创建之前创建吗?你不能确定。