Copy operations (copy constructors and copy assignment operators) are expected to copy the salient properties of a source object into the destination object, with the resulting object being a "copy" of the original. What is considered to be a salient property of the type is type-dependent, but for types that expose comparison or equality operators, includes any properties used for those comparison operations. This expectation leads to assumptions in code that a copy operation results in a destination object with a value representation that is equivalent to the source object value representation. Violation of this basic assumption can lead to unexpected behavior.
Ideally, the copy operator should have an idiomatic signature. For copy constructors, that is T(const T&);
and for copy assignment operators, that is T& operator=(const T&);
. Copy constructors and copy assignment operators that do not use an idiomatic signature do not meet the requirements for of the CopyConstructible
or CopyAssignable
constraints used with the STL concept, respectively. This precludes the type from being used with common standard library functionality [ISO/IEC 14882-2014].
When implementing a copy operator, do not mutate any externally observable members of the source object operand or globally accessible information. Externally observable members include, but are not limited to, members that participate in comparison or equality operations and , members whose values are exposed via public APIs, and global variables.
For example, in C++03, std::auto_ptr
had the following copy operation signatures (note: std::auto_ptr
was deprecated in C++11) [ISO/IEC 14882-2003]:
...