implement a single-instance class in C++
时间: 2024-04-10 21:34:42 浏览: 22
In C++, you can implement a single-instance class using the Singleton design pattern. Here's an example:
```cpp
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
// Other member functions and variables
private:
Singleton() {
// Private constructor to prevent direct instantiation
}
// Disable copy constructor and assignment operator
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
```
In this example, the `Singleton` class has a private constructor to prevent direct instantiation. The `getInstance()` static member function provides a way to access the single instance of the class. It uses a static local variable to ensure that only one instance is created.
To use the singleton class, you can call `Singleton::getInstance()` to obtain the instance:
```cpp
Singleton& singletonObj = Singleton::getInstance();
```
This ensures that only one instance of the `Singleton` class is created throughout the program.
Note that this implementation is not thread-safe. If you require thread safety, additional synchronization mechanisms, such as mutexes, can be used to ensure proper initialization and access to the single instance.