#include <iostream>
#include <memory>
using namespace std;
class Counter {
private:
static unique_ptr<Counter> instance; // Singleton instance
int count; // Simple counter
// Private constructor
Counter() : count(0) {
cout << "Counter instance created!" << endl;
}
public:
// Delete copy constructor and assignment operator
Counter(const Counter&) = delete;
Counter& operator=(const Counter&) = delete;
// Static method to get the single instance
static Counter* getInstance() {
if (!instance) {
instance.reset(new Counter());
}
return instance.get();
}
// Increment and display count
void increment() {
count++;
cout << "Count: " << count << endl;
}
};
// Initialize the static unique_ptr
unique_ptr<Counter> Counter::instance = nullptr;
int main() {
Counter* counter1 = Counter::getInstance();
counter1->increment(); // Count: 1
Counter* counter2 = Counter::getInstance();
counter2->increment(); // Count: 2
// Check if both instances are the same
cout << (counter1 == counter2 ? "Singleton works!" : "Singleton failed!") << endl;
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: