如何在 C++ 中正确实现线程安全的 Singleton 模式
大家好!我是一名 C++ 初学者,正在尝试理解 Singleton 模式。我了解到这是一种创建型模式,它确保一个类只有一个实例,并提供一个全局访问点。
我为日志器编写了一个简单实现:
```cpp
class Logger {
public:
static Logger* getInstance() {
if (instance == nullptr) {
instance = new Logger();
}
return instance;
}
void log(const std::string& msg) {
std::cout << msg << std::endl;
}
private:
Logger() {}
static Logger* instance;
};
Logger* Logger::instance = nullptr;
```
但我有几个疑问:
1. 在多线程环境中,如果两个线程同时调用 getInstance(),可能会创建多个实例。
2. 没有对象删除机制——会导致内存泄漏。
3. 我见过不同的方案:使用 mutex、std::call_once、magic statics。哪种是正确的?