According to CppCoreGuidelines C.60 and C.63, copy assignment operator (e.g Foo& operator=(const Foo& x)
) and move assignement operator (e.g Foo& operator=(const Foo&& x)
) should be declared non-virtual.
Can you explain me the reason of this recommandation ? As suggested by this answer, I imagine that this is to avoid leaks of memory but I don't see exactly how the use of virtual will induce it.
CodePudding user response:
There is no reason why a copy or move assignment operator should be virtual. Making it virtual possibly incurs costs associated with having virtual functions (e.g. the requirement to allocate a vptr within each object of the class) for no benefit.
Let's say you have a class Base
, which has a virtual copy assignment operator:
virtual Base& operator=(const Base&);
What will happen when you write a derived class, class Derived : public Base
? It will have its own copy assignment operator:
Derived& operator=(const Derived&); // possibly also virtual
If you don't declare such an operator, the compiler will implicitly declare one with this signature (modulo some details that are not relevant here).
Because the derived class's copy assignment operator has a different argument type from that of the base class, there is no overriding relationship between them. And there's no point in writing a virtual function if it's never going to be overridden.