...
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 the following implementation of std::sort()
that implements the quick sort algorithm:.
Code Block |
---|
// ... value_type pivot_element = *mid_point; // ... |
At this point, the sorting algorithm assumes that pivot_element
and *mid_point
have equivalent value representations and will compare equal. However, for std::auto_ptr
, this is not the case because *mid_point
has been mutated, and mutated and results in unexpected behavior.
In C++11, the std::unique_ptr
smart pointer class was introduced as a replacement for std::auto_ptr
to better specify the ownership semantics of pointer objects. Rather than mutate the source argument in a copy operation, std::unique_ptr
explicitly deletes the copy constructor and copy assignment operator, and instead uses a move constructor and move assignment operator. Subsequently, std::auto_ptr
was deprecated in C++11.
...
Copy operations that mutate the source operand or global state can lead to unexpected program behavior. In the case of using Using such a type in a Standard Template Library container or algorithm , this can also lead to undefined behavior.
...
[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 052005] | "Rvalue Reference Recommendations for Chapter 20" |
...