如果我在静态对象中获取 this
并将其存储在 Singleton 对象的 vector 中,我可以假设指针在程序的整个生命周期内都指向该对象吗?
最佳答案
一般来说,您不能这样假设,因为在不同翻译单元中静态对象的创建顺序是未指定的。在这种情况下它会起作用,因为只有一个翻译单元:
#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;
}
输出:
Singleton contains: 100
但是如果 A::staticA
在不同的翻译单元中定义怎么办?它会在 static Singleton
创建之前创建吗?你不能确定。
关于c++ - 静态对象的this指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548118/