What's the use of the private copy constructor in c++

后端 未结 7 1418
抹茶落季
抹茶落季 2020-11-29 23:44

Why do people define a private copy constructor?

When is making the copy constructor and the assignment operator private a good design?

If there are no membe

7条回答
  •  心在旅途
    2020-11-30 00:13

    One use case is the singleton pattern where there can only be exactly one instance of a class. In this case, you need make your constructors and assignment operator= private so that there is no way of creating more than one object. The only way to create an object is via your GetInstance() function as shown below.

    // An example of singleton pattern
    class CMySingleton
    {
    public:
      static CMySingleton& GetInstance()
      {
        static CMySingleton singleton;
        return singleton;
      }
    
    // Other non-static member functions
    private:
      CMySingleton() {}                                  // Private constructor
      ~CMySingleton() {}
      CMySingleton(const CMySingleton&);                 // Prevent copy-construction
      CMySingleton& operator=(const CMySingleton&);      // Prevent assignment
    };
    
    int main(int argc, char* argv[])
    {
      // create a single instance of the class
      CMySingleton &object = CMySingleton::GetInstance();
    
      // compile fail due to private constructor
      CMySingleton object1;
      // compile fail due to private copy constructor
      CMySingleton object2(object);
      // compile fail due to private assignment operator
      object1 = object;
    
      // ..
      return 0;
    }
    

提交回复
热议问题