How to create class with only one instance in C++

2019-09-01 06:16发布

问题:

This question already has an answer here:

  • Single class instance C++ 3 answers

Is there any way to allow only one instance of a class in C++? If there is, please expain to me. Thank you.

回答1:

This is the singleton pattern. You can achieve this via a public static attribute and a private constructor:

class Singleton {
    public:
        static Singleton * const singleton;
    private:
        Singleton(void) {}
};
Singleton * const Singleton::singleton = new Singleton();

Edit: Good point from Dan Watkins; If you really want to be draconian about it, you can disallow copy and assignment by also explicitly declaring those methods private:

    private:
        Singleton(void) {}
        Singleton(Singleton& other) {}
        Singleton& operator=(Singleton& other) {}


标签: c++ class