C++中实现单例:
- 隐藏构造函数和析构函数
- 隐藏拷贝赋值和拷贝构造函数
=delete
- 使用静态对象和函数实现单例的唯一访问接口
- 线程安全 - 使用
mutex
和两次检查为空
代码(摘自C++单例详解)
/**
* 单例类的静态函数`GetInstance`提供了获取单例的唯一接口
* The Singleton class defines the `GetInstance` method that serves as an
* alternative to constructor and lets clients access the same instance of this
* class over and over.
*/
class Singleton
{
/**
* 单例类的构造函数、析构函数需要设置为private防止`new`/`delete`操作符的调用
* The Singleton's constructor/destructor should always be private to
* prevent direct construction/desctruction calls with the `new`/`delete`
* operator.
*/
private:
static Singleton * pinstance_;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* 禁用拷贝构造 - 不可拷贝;
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* 禁用拷贝赋值 - 不可赋值
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
/**
* 提供唯一访问接口的静态方法。第一次运行初始化静态单例对象,后续调用直接返回
* This is the static method that controls the access to the singleton
* instance. On the first run, it creates a singleton object and places it
* into the static field. On subsequent runs, it returns the client existing
* object stored in the static field.
*/
static Singleton *GetInstance(const std::string& value);
/**
* 单例类的其他业务逻辑
* Finally, any singleton should define some business logic, which can be
* executed on its instance.
*/
void SomeBusinessLogic()
{
// ...
}
std::string value() const{
return value_;
}
};
/**
* 静态方法类外定义
* Static methods should be defined outside the class.
*/
Singleton* Singleton::pinstance_{nullptr};
std::mutex Singleton::mutex_;
/**
* 第一次调用需要锁住互斥量,之后再次检查确保单例尚未被创建
* The first time we call GetInstance we will lock the storage location
* and then we make sure again that the variable is null and then we
* set the value. RU:
*/
Singleton *Singleton::GetInstance(const std::string& value)
{
if (pinstance_ == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (pinstance_ == nullptr)
{
pinstance_ = new Singleton(value);
}
}
return pinstance_;
}
void ThreadFoo(){
// Following code emulates slow initialization.
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
// Following code emulates slow initialization.
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
return 0;
}