One instance of a C ++ class

Is it possible to create a class that could be built only once? If you try to create another instance, a compile-time error should occur.

+3
source share
3 answers

Activation is dynamic at runtime. Compilation errors during compilation. Thus, the answer is no, it is impossible to get a compilation error for any second instance.

However, you can use singleton, but be very careful about whether this is really necessary.

+4
source

Why compile the error? I think you just need to develop a Singleton design template. Look here

0
source

singleton classess,

.

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
    };
0

All Articles