In C++11, you can implement the Singleton pattern using the following steps:
-
Create a class and make its constructor, copy constructor, and assignment operator private to prevent direct instantiation and copying.
-
Provide a static member function that returns a reference to the single instance of the class.
-
Use std::atomic and std::mutex to ensure thread safety during the creation of the instance.
-
Make sure to use the double-check locking mechanism to avoid unnecessary locking.
Here's an example implementation of the Singleton pattern in C++11:
#include <iostream>
#include <mutex>
class Singleton {
private:
static std::atomic<Singleton*> instance;
static std::mutex mutex;
Singleton() {
std::cout << "Singleton instance created" << std::endl;
}
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* getInstance() {
Singleton* tmpInstance = instance.load(std::memory_order_relaxed); // Acquire the instance if already created
std::atomic_thread_fence(std::memory_order_acquire); // Ensure ordering before instance check
if (tmpInstance == nullptr) {
std::lock_guard<std::mutex> lock(mutex); // Lock if instance is still null
tmpInstance = instance.load(std::memory_order_relaxed); // Check again after acquiring lock
if (tmpInstance == nullptr) {
tmpInstance = new Singleton(); // Create new instance if still null
std::atomic_thread_fence(std::memory_order_release); // Ensure ordering before storing the instance
instance.store(tmpInstance, std::memory_order_relaxed); // Store the new instance
}
}
return tmpInstance;
}
void showMessage() {
std::cout << "Hello from Singleton!" << std::endl;
}
};
std::atomic<Singleton*> Singleton::instance(nullptr);
std::mutex Singleton::mutex;
int main() {
Singleton* singleton1 = Singleton::getInstance();
singleton1->showMessage();
Singleton* singleton2 = Singleton::getInstance();
singleton2->showMessage();
// Both singleton1 and singleton2 are pointers to the same instance
if (singleton1 == singleton2) {
std::cout << "Both pointers refer to the same instance" << std::endl;
}
return 0;
}
In this example, the getInstance() function is responsible for creating and returning the single instance of the Singleton. The std::atomic type is used to guarantee atomic operations on the instance pointer, ensuring its safety in a multi-threaded environment. The std::mutex type is used to lock the critical section while creating the instance.