If you disable the copy constructor and the assignment operator in the base class, do you need to do the same in derived classes?
1 answer
It is not necessary to do this. For example, there is an auxiliary class boost::non_copyable
which is used to prohibit copying.
However, when you try to copy, the error message will be written only about boost::non_copyable
, but not about the heir class, which boost::non_copyable
it difficult to understand exactly where the error occurred.
Therefore, it is better to prohibit copying explicitly, in the heir class. The recommended way is =delete;
struct X { X(const X&) = delete; X& operator=(const X&) = delete; };
If the code is compiled for C ++ 03, then the constructor and the assignment operator must be declared in the private
section, and not defined. Then there will be either a compilation error (due to private) or a link error.
struct X { private: X(const X&); // noncopyable X& operator=(const X&); // noncopyable };
- four
= delete
appeared in 11 standard. If the version of the standard used by the compiler is more early (more precisely, not used, but "that which it adheres to"), then you need to declare the operator, but do not write anything in the body.X(Xconst&);
- isnullxbh