2016-09-17 1 views
7

静的オブジェクトにthisを入れて、それをシングルトンオブジェクトのベクトルに格納すると、プログラムの全ライフタイム中にポインタがオブジェクトを指していると仮定できますか?この静的オブジェクトのポインタ

+1

このようにシングルトンを実行すると、管理シングルトンからインスタンスにアクセスしている間は、次のような順序でインスタンスにアクセスする限り、http://stackoverflow.com/questions/6993400/managing-a-singleton-destructor/6993501#6993501創造と破壊は事実上保証されています。 – Nim

答えて

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が作成される前に作成されますか?あなたは確信が持てません。

関連する問題