Single class instance C++

2019-04-11 16:13发布

Is it possible to create a class which could be constructed just one time? If you would try to create an other instance of it, a compile-time error should occure.

标签: c++ class
3条回答
劳资没心,怎么记你
2楼-- · 2019-04-11 16:49

Instantiation is dynamic, at run time. Compilation errors are at compile time. So the answer is no, it's not possible to get a compilation error on any second instantiation.

You can however use a singleton, but do consider very carefully whether it's really needed.

查看更多
迷人小祖宗
3楼-- · 2019-04-11 17:01

The classes with only one instances are called singleton classess,

There are many ways to perform that. The simplest is shown below

class MySingleton
    {
    public:
      static MySingleton& Instance()
      {
        static MySingleton singleton;
        return singleton;
      }

    // Other non-static member functions
    private:
      MySingleton() {};                                 // Private constructor
      MySingleton(const MySingleton&);                 // Prevent copy-construction
      MySingleton& operator=(const MySingleton&);      // Prevent assignment
    };
查看更多
Summer. ? 凉城
4楼-- · 2019-04-11 17:05

Why compile error? You just need to implement Singleton design pattern, I think. Look here

查看更多
登录 后发表回答