Can a derived class be made uncopyable by declaring copy constructor/operator private in base class?

橙三吉。 提交于 2019-12-05 04:48:04

This should prevent the compiler from generating a copy constructor for derived classes which do not declare one explicitly. However, nothing prevents a derived class from explicitly declaring a copy constructor which will do something else than call the copy constructor of Base.

There is no way to make sure derived classes are instantiable but not copyable.

Rather than declaring the copy constructor/operator as private declare them as deleted. Declaring copy constructor/operator as private is not the best solution to making the derived classes non-copyable. If you want the base class to be completely non-copyable then declare the copy constructor/operator as deleted as copy can still take place inside the member functions of Base as private members are accessible to that class's functions. You can use the C++11 feature of delete:

Base(const Base&) = delete; // copy constructor
Base& operator=(const Base&) = delete; // copy-assignment operator

But declaring copy constructor/operator as private is also right as long as you're aware that copy can still take place inside the member functions of Base.

In C++11 and later there is the option to declare a constructor deleted.

struct X {
  X( const X& ) = delete;
};

Now, anything derived from X that rely on the copy-constructor will not compile. This is most useful when you want to avoid problems because the compiler auto-generates constructors...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!