Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated with move operations

...

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 results unexpected behavior.

Generally, a copy operation that mutates the source operand is a safe operation to perform only when the source operand is at the end of its lifetime, because the value representation of the source operand is not important. Such a situation is a good candidate for a move operation instead of a copy operation.

Noncompliant Code Example

...

In this compliant solution, the copy operations for A no longer mutate the source operand, ensuring that vector contains equivalent copies of Obj:. Instead, A has been given move operations that perform the mutation when it is safe to do so.

Code Block
bgColor#ccccff
langcpp
#include <algorithm>
#include <vector>

class A {
  int M;
  
public:
  A() : M(0) {}
  explicit A(int I) : M(I) {}
  
  A(const A &Other) : M(Other.M) {}
  A(A &&Other) : M(Other.M) { Other.M = 0; }
  
  A& operator=(const A &Other) {
    if (&Other != this) {
      M = Other.M;
    }
    return *this;
  }
 
  A& operator=(A &&Other) {
    M = Other.M;
    Other.M = 0;
    return *this;
  }
  
  int Get_M() const { return M; }
};

void f() {
  std::vector<A> V{10};
  A Obj(12);
  std::fill(V.begin(), V.end(), Obj);
}

...