1
我有一個Singleton實現,我不確定它包含哪些缺點。有誰能告訴我這個實現有多好?帶有靜態成員實例的單身人士
template <class Child>
class Singleton {
public:
inline static Child& Instance() {
return Instance_;
}
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
protected:
Singleton() = default;
private:
static Child Instance_;
};
template <typename Child> Child Singleton<Child>::Instance_;
我知道斯科特邁爾斯一個Singleton實現定義靜態Instance_
的GetInstance()
函數內的。
inline static Child& Instance() {
static Child Instance_;
return Instance_;
}
但不存在額外的開銷參與其中,因爲它必須檢查每一個函數調用時是否Instance_
已經被初始化的時間。
可能是一個很好的問題http://codereview.stackexchange.com – RhinoDevel
只有當對象正在創建時的差異。在你的情況下,對象將在主要功能之前構建,邁耶斯的技巧顯示延遲建設。關於表現,這至少是你應該關心的部分。正如Meyers所說 - 除非profiler這樣說,否則不要進行優化。 – jonezq