我需要单例中的静态变量 class 吗?
Do I need static variables in a singleton class?
采用以下代码。如果我要在这个 class 中添加一些私有成员数据,比如说 std::vector,我会把它设为静态吗?
#include <string>
class Logger{
public:
static Logger* Instance();
bool openLogFile(std::string logFile);
void writeToLogFile();
bool closeLogFile();
private:
Logger(){}; // Private so that it can not be called
Logger(Logger const&){}; // copy constructor is private
Logger& operator=(Logger const&){}; // assignment operator is private
static Logger* m_pInstance;
};
**代码示例无耻地取自here
惯用语,不。除此之外,没有什么能阻止你这样做。
请记住,如果它是 static
,则需要在程序启动时定义它并在进入 main
之前初始化该成员。
如果不是 static
,它将在创建 m_pInstance
时进行初始化(如果您需要延迟初始化,这会很有用)。
最大的问题是初始化顺序。在 C++ 中,单例习语
通常用于解决初始化问题的顺序,所以这是
可能是一个问题:如果成员是静态的,你不能确定
在您尝试使用它们之前,它们已经被构建。
采用以下代码。如果我要在这个 class 中添加一些私有成员数据,比如说 std::vector,我会把它设为静态吗?
#include <string>
class Logger{
public:
static Logger* Instance();
bool openLogFile(std::string logFile);
void writeToLogFile();
bool closeLogFile();
private:
Logger(){}; // Private so that it can not be called
Logger(Logger const&){}; // copy constructor is private
Logger& operator=(Logger const&){}; // assignment operator is private
static Logger* m_pInstance;
};
**代码示例无耻地取自here
惯用语,不。除此之外,没有什么能阻止你这样做。
请记住,如果它是 static
,则需要在程序启动时定义它并在进入 main
之前初始化该成员。
如果不是 static
,它将在创建 m_pInstance
时进行初始化(如果您需要延迟初始化,这会很有用)。
最大的问题是初始化顺序。在 C++ 中,单例习语 通常用于解决初始化问题的顺序,所以这是 可能是一个问题:如果成员是静态的,你不能确定 在您尝试使用它们之前,它们已经被构建。