给出一个c++的,线程安全的,用shared_ptr封装的单例类的代码示例
时间: 2023-04-09 08:04:55 浏览: 53
当然可以,以下是一个线程安全的、使用 shared_ptr 封装的单例类的示例代码:
```c++
#include <memory>
#include <mutex>
class Singleton {
public:
static Singleton& getInstance() {
static std::shared_ptr<Singleton> instance;
static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);
if (!instance) {
instance.reset(new Singleton);
}
return *instance;
}
void doSomething() {
// do something
}
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
```
这个示例中,我们使用了一个静态的 shared_ptr 对象来保存单例实例。在 getInstance() 方法中,我们使用了一个互斥锁来保证线程安全,并在第一次调用时创建单例实例。最后,我们返回 shared_ptr 对象的引用,以确保单例实例不会被销毁。