Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: elim self-assignment test

...

Code Block
bgColor#ccccFF
langcpp
#include <cstring>
 
class IntArray {
  int *array;
  std::size_t nElems;
public:
  // ...

  ~IntArray() {
    delete[] array;
  }

  IntArray(const IntArray& that); // nontrivial copy constructor

  IntArray& operator=(const IntArray &rhs) {
    if (this != &rhs) {
      int *tmp = nullptr;
      if (rhs.nElems) {
        tmp = new int[rhs.nElems];
        std::memcpy(tmp, rhs.array, nElems * sizeof(*array));
      }
      delete[] array;
      array = tmp;
      nElems = rhs.nElems;
    }
    return *this;
  }

  // ...
};

...