Versions Compared

Key

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

...

Code Block
#include <utility>
 
struct S { /* ... */ }
 
void f() {
  S s;
  s = s; // Self-copy assignment
  s = std::move(s); // Self-move assignment
}

User-provided copy and move assignment operators must properly handle self-assignment.Copy Assignment

The postconditions required for copy assignment are specified by the C++ Standard, [utility.arg.requirements], Table 23 [ISO/IEC 14882-2014], which states that for x = y, the value of y is unchanged. When &x == &y, this postcondition translates into the values of both x and y remaining unchanged. A naive implementation of copy assignment will destroy object-local resources in the process of copying resources from the given parameter. If the given parameter is the same object as the local object, the act of destroying object-local resources will invalidate them. The subsequent copy of those resources will be left in an indeterminate state, which violates the postcondition.

...

The C++ Standard, [copyassignable], specifies that types must ensure that self-copy assignment leave the object in a consistent state when passed to Standard Template Library functions. Since objects of Standard Template Library types are used in contexts where CopyAssignable is required, Standard Template Library types are required to gracefully handle self-copy assignment.

Move Assignment

The postconditions required for a move assignment are specified by the C++ Standard, [utility.arg.requirements], Table 22 [ISO/IEC 14882-2014], which states that for x = std::move(y), the value of y is left in a valid but unspecified state. When &x == &y, this postcondition translates into the values of both x and y remaining in a valid but unspecified state. Leaving the values in an unspecified state may result in vulnerabilities leading to exploitable code.

A user-provided move assignment operator must prevent self-move assignment from leaving the object in a valid but unspecified state. Akin to copy assignment, it can be accomplished by self-assignment tests, move-and-swap, or other idiomatic design patterns.

...

Page properties
hiddentrue

This rule used to also cover move operations, but there were enough questions about how to formulate that part of the rule to warrant removing that information. See r58 of the rule for the old content and the comments section for problems. Specifically, because the STL does not require objects to be resilient to self-move, it makes user-defined types that use STL types difficult to work with. It may be that we need to disallow a = std::move(a);, but that may be difficult due to template metaprogramming.

Noncompliant Code Example

In this noncompliant code example, the copy and move assignment operators do operator does not protect against self-assignment. If self-copy assignment occurs, this->s1 is deleted, which results in rhs.s1 also being deleted. The invalidated memory for rhs.s1 is then passed into the copy constructor for S, which can result in dereferencing an invalid pointer. If self-move assignment occurs, it is dependent on the implementation of std::swap as to whether s1 is left in a valid but unspecified state.

Code Block
bgColor#FFcccc
langcpp
#include <new>
 
struct S { /* ... */ }; // Has nonthrowing copy constructor
 
class T {
  int n;
  S *s1;
 
public:
  T(const T &rhs) : n(rhs.n), s1(rhs.s1 ? new S(*rhs.s1) : nullptr) {}
  T(T &&rhs) noexcept : n(rhs.n), s1(rhs.s1) { rhs.s1 = nullptr; }
  ~T() { delete s1; }
 
  // ...
 
  T& operator=(const T &rhs) {
    n = rhs.n;
    delete s1;
    s1 = new S(*rhs.s1);
    return *this;
  }
 
  T& operator=(T &&rhs) noexcept {
    n = rhs.n;
    s1 = rhs.s1;
    return *this;
  }
};

Compliant Solution (Self-Test)

This compliant solution guards against self-assignment by testing whether the given parameter is the same as this. If self-assignment occurs, the result of operator= is a noop; otherwise, the copy and move proceeds as in the original example.

Code Block
bgColor#ccccff
langcpp
#include <new>
 
struct S { /* ... */ }; // Has nonthrowing copy constructor
 
class T {
  int n;
  S *s1;
 
public:
  T(const T &rhs) : n(rhs.n), s1(rhs.s1 ? new S(*rhs.s1) : nullptr) {}
  T(T &&rhs) noexcept : n(rhs.n), s1(rhs.s1) { rhs.s1 = nullptr; }
  ~T() { delete s1; }

  // ...
 
  T& operator=(const T &rhs) {
    if (this != &rhs) {
      n = rhs.n;
      delete s1;
      try {
        s1 = new S(*rhs.s1);
      } catch (std::bad_alloc &) {
        s1 = nullptr; // For basic exception guarantees
        throw;
      }
    }
    return *this;
  }
 
  T& operator=(T &&rhs) noexcept {
    if (this != &rhs) {
      n = rhs.n;
      s1 = rhs.s1;
    }
    return *this;
  }
};

Note that this solution does not provide a strong exception guarantee for the copy assignment. Specifically, if an exception is called when evaluating the new expression, this has already been modified. However, this solution does provide a basic exception guarantee because no resources are leaked and all data members contain valid values. Consequently this code complies with ERR56-CPP. Guarantee exception safety.

Compliant Solution (Copy and Swap)

This compliant solution avoids self-copy assignment by constructing a temporary object from RHS that is then swapped with *this. This compliant solution can provide a strong exception guarantee because swap() will never be called if resource allocation results in an exception being thrown while creating the temporary object. It avoids self-move assignment by testing for self-assignment, as in the previous compliant solution.

Code Block
bgColor#ccccff
langcpp
#include <new>
#include <utility>
 
struct S { /* ... */ }; // Has nonthrowing copy constructor
 
class T {
  int n;
  S *s1;
 
public:
  T(const T &rhs) : n(rhs.n), s1(rhs.s1 ? new S(*rhs.s1) : nullptr) {}
  T(T &&rhs) noexcept : n(rhs.n), s1(rhs.s1) { rhs.s1 = nullptr; }
  ~T() { delete s1; }

  // ...
 
  void swap(T &rhs) noexcept {
    using std::swap;
    swap(n, rhs.n);
    swap(s1, rhs.s1);
  }
 
  T& operator=(const T &rhs) noexcept {
    T(rhs).swap(*this);
    return *this;
  }
 
  T& operator=(T &&rhs) noexcept {
    if (&rhs != this) {
      n = rhs.n;
      s1 = rhs.s1;
    }
    return *this;
  }
};

...

OOP54-CPP-EX1: Self-swap is trivially self-move assignment safe. Calling std::swap(x, x) results in an operation that moves the resources from x into a temporary object, performs a self-move assignment that should have no ill-effect on the already-moved-from state of x, and finally moves the resources from the temporary object back into x with the end result that the resources stored within x should be unchanged. Because of how pervasive the use of std::swap() is within the Standard Template Library and the unlikelihood that a self-swap would cause undefined behavior in practice, guarding against self-move assignment through self-swap is not required.

Risk Assessment

Allowing a copy assignment operator to corrupt an object could lead to undefined behavior. Allowing a move assignment operator to leave an object in a valid but unspecified state could lead to abnormal program execution.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OOP54-CPP

Low

Probable

High

P2

L3

Automated Detection

Tool

Version

Checker

Description

Parasoft C/C++test9.5OOP-34 
PRQA QA-C++
Include Page
PRQA QA-C++_V
PRQA QA-C++_V
4072, 4073, 4075, 4076 

Related Vulnerabilities

Search for other vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

This rule is a partial subset of OOP58-CPP. Copy operations must not mutate only the destination of the copythe source object when copy operations do not gracefully handle self-assignment, because the copy operation may mutate both the source and destination objects (due to them being the same object).

Bibliography

[Henricson 97]Rule 5.12, Copy assignment operators should be protected from doing destructive actions if an object is assigned to itself
[ISO/IEC 14882-2014]Subclause 17.6.3.1, "Template Argument Requirements"
Subclause 17.6.4.9, "Function Arguments"
[Meyers 05]Item 11, "Handle Assignment to Self in operator="
[Meyers 14] 

...