c++单例模式代码实现
时间: 2023-08-01 16:15:30 浏览: 80
以下是C++中单例模式的代码实现:
```cpp
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
```
在该实现中,`Singleton`是一个单例类,其构造函数为私有,因此外部无法直接创建该类的实例。为了访问该类的唯一实例,需要使用`getInstance`方法,该方法会在第一次调用时创建`Singleton`类的唯一实例,并在后续调用时返回该实例的引用。`instance`是一个静态成员变量,用于保存`Singleton`类的唯一实例。注意,该实现虽然满足单例模式的要求,但不是线程安全的,需要在多线程环境下进行改进。
相关问题
c++ 单例模式代码
以下是 C++ 实现单例模式的代码:
```cpp
class Singleton {
private:
static Singleton* instance; // 声明静态指针变量
// 私有构造函数和析构函数
Singleton() {}
~Singleton() {}
public:
static Singleton* getInstance() { // 获取实例的静态方法
if (instance == nullptr) {
instance = new Singleton(); // 如果实例不存在,则创建实例
}
return instance;
}
void doSomething() { // 单例类的成员函数
// ...
}
};
// 初始化静态指针变量
Singleton* Singleton::instance = nullptr;
```
在使用时,可以通过调用 `Singleton::getInstance()` 方法来获取单例实例,然后通过实例调用成员函数 `doSomething()` 进行操作。
C++多线程单例模式代码实现
以下是C++中多线程安全的单例模式代码实现:
```cpp
#include <mutex>
class Singleton {
private:
static Singleton* instance;
static std::mutex mutex;
Singleton() {}
public:
static Singleton* getInstance() {
std::lock_guard<std::mutex> lock(mutex);
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex;
```
在该实现中,我们使用了`std::mutex`来保证在多线程环境下单例类的唯一性。`mutex`是一个静态成员变量,用于保证在多线程环境下对`instance`的访问是互斥的。在`getInstance`方法中,我们使用`std::lock_guard<std::mutex>`来保证在访问`instance`时,互斥锁被正确地加锁和解锁。这样就可以保证在多线程环境下,单例类的唯一实例只会被创建一次。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)