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

2019-09-01 05:28发布

This question already has an answer here:

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

标签: c++ class
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-01 06:11

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) {}
查看更多
登录 后发表回答