0
我知道只有在初始化靜態變量時纔有基本的保證。對於我來說,最重要的是不能保證的是不同編譯單元中變量的初始化順序,這引發了下面的問題。getInstance - 類與方法static
我一直寫我的單身類是這樣的:
class A {
...
public:
static std::shared_ptr<A> getInstance();
private:
static std::shared_ptr<A> _instance;
}
== A.cpp ==
std::shared_ptr<A> A::getInstance() {
if(!_instance)
_instance = std::make_shared<A>();
return _instance;
}
但是,據我瞭解,這並不保證實例已初始化(因此調用operator布爾是有效的),如果我調用該函數在任何其他靜態對象的構造函數中(可能會在主啓動執行之前發生)。
我的新思路如下:
class A {
...
public:
static std::shared_ptr<A> getInstance();
}
== A.cpp ==
A& A::getInstance() {
static std::shared_ptr<A> _instance = std::make_shared<A>();
return _instance;
}
這在我看來不只是清潔,但代碼也更好,因爲現在我有初始化的保證的順序。
我的假設是否正確?
既然你知道'_instance'保證在第一次調用'getInstance'時被初始化,爲什麼你仍然需要'if'語句? – Nard
因爲_instance不包含值。默認初始化一個std :: shared_ptr會在其中存儲一個空指針。 – Thalhammer
如果是這樣,爲什麼不立即用'new A'初始化'shared_ptr'? – Nard