Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 of the CopyConstructible or CopyAssignable 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, 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]:

Copy constructorauto_ptr(auto_ptr &A);
Copy assignmentauto_ptr& operator=(auto_ptr &A);

Both copy construction and copy assignment would mutate the source argument, A, by effectively calling this->reset(A.release()). However, this invalidated assumptions made by standard library algorithms such as std::sort(), which may need to make a copy of an object for later comparisons [Hinnant 05]. Consider an implementation of std::sort() that implements the quick sort algorithm:

...

Related Guidelines

  

Bibliography

[ISO/IEC 14882-2014]Subclause 12.8, "Copying and Moving Class Objects"
Table 21, "CopyConstructible Requirements"
Table 23, "CopyAssignable Requirements" 
[ISO/IEC 14882-2003] 
[Hinnant 05]"Rvalue Reference Recommendations for Chapter 20"

...