[英]this pointer of a static object
如果我將this
放在一個靜態對象中並將其存儲在Singleton對象的向量中,我可以假設指針在程序的整個生命周期中指向該對象嗎?
通常,您不能假設,因為未指定在不同翻譯單元中創建靜態對象的順序。 在這種情況下它會起作用,因為只有一個翻譯單元:
#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
之前創建它? 你不能確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.