Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated the CS so it has a basic exception guarantee

...

Code Block
bgColor#ccccff
langcpp
#include <new>
#include <utility>
 
struct S { /* ... */ };
 
class T {
  int N;
  S *S1;
 
public:
  T(const T &RHS) : N(RHS.N), S1(RHS.S1 ? new S1(*RHS.S1) : nullptr) {}
  T(T &&RHS) : N(RHS.N), S1(RHS.S1) noexcept { 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;
      std::swap(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.

Compliant Solution (Copy and Swap)

...