这个静态对象的指针

时间:2016-09-17 14:47:48

标签: c++ static

如果我在静态对象中取this并将其存储在Singleton对象的向量中,我可以假设指针在程序的整个生命周期内指向该对象吗?

1 个答案:

答案 0 :(得分:2)

通常,您不能假设,因为未指定在不同翻译单元中创建静态对象的顺序。在这种情况下它会起作用,因为只有一个翻译单元:

#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创建之前创建吗?你无法确定。