Static - Singleton example

 avatar
tuhuuduc
c_cpp
7 months ago
1.1 kB
7
Indexable
Never
#include <iostream>

class Singleton {
public:
    // Static member function to get the instance of Singleton
    static Singleton& getInstance() {
        // Static local variable to hold the instance
        static Singleton instance;
        return instance;
    }

    // Public member function to demonstrate the Singleton
    void demo() {
        std::cout << "Singleton instance is being used." << std::endl;
    }
 private
    // Private constructor to prevent instantiation
    Singleton() = default;
 public:
    // Private destructor to prevent deletion
    ~Singleton() {
        std::cout << "Singleton instance destroyed." << std::endl;
    }

    // Private copy constructor and assignment operator to prevent cloning and assignment
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};

int main() {
    // Get the Singleton instance
    Singleton& singleton = Singleton::getInstance();

    // Use the Singleton instance
    singleton.demo();

    return 0;
}
Leave a Comment