Rule A6-2-1 (required, implementation, automated)
Move and copy assignment operators shall either move or respectively copy base classes and data members of a class, without any side effects.
Rationale
It is expected behavior that the move/copy assigned operator are only used to move/copy the object of the class type and possibly set moved-from object to a valid state. Those operators are not supposed to provide any performance overhead or side effects that could affect moving or copying the object. Note: Class members that are not essential for a class invariant may not need to be moved/copied (e.g. caches, debug information).
Example
// $Id: A6-2-1.cpp 305786 2018-01-30 08:58:33Z michal.szczepankiewicz $
#include <cstdint>
#include <utility>
class A
{
public:
A& operator=(const A& oth) // Compliant
{
if(&oth == this)
{
return *this;
}
x = oth.x;
return *this;
}
private:
std::int32_t x;
};
class B
{
public:
~B() { delete ptr; }
//compliant
B& operator=(B&& oth)
{
if(&oth == this)
{
return *this;
}
ptr = std::move(oth.ptr);
// Compliant - this is not a side-effect, in this
// case it is essential to leave moved-from object
// in a valid state, otherwise double deletion will
// occur.
return *this;
}
private:
std::int32_t* ptr;
};
class C
{
public:
C& operator=(const C& oth)
{
if(&oth == this)
{
return *this;
}
x = oth.x % 2; // Non-compliant - unrelated side-effect
return *this;
}
private:
std::int32_t x;
};
class D
{
public:
explicit D(std::uint32_t a) : a(a), noOfModifications(0) {}
D& operator=(const D& oth)
{
if(&oth == this)
{
return *this;
}
a = oth.a;
//compliant, not copying the debug information about number of modifications
return *this;
}
void SetA(std::uint32_t aa)
{
++noOfModifications;
a = aa;
}
std::uint32_t GetA() const noexcept
{
return a;
}
private:
std::uint32_t a;
std::uint64_t noOfModifications;
};
See also
JSF December 2005 [8]: AV Rule 83: An assignment operator shall assign all data members and bases that affect the class invariant (a data element representing a cache, for example, would not need to be copied).