120. Copy Semantics-II

Question.1

A developer uses the copy-and-swap idiom for exception-safe assignment:

class Buffer {
   int* ptr; int size;
public:
   Buffer(int n) : size(n), ptr(new int[n]) {}
   Buffer(const Buffer& o) : size(o.size), ptr(new int[o.size]) {
       memcpy(ptr, o.ptr, size*sizeof(int));
   }
   ~Buffer() { delete[] ptr; }

   Buffer& operator=(Buffer other) { // Note: by VALUE
       std::swap(ptr, other.ptr);
       std::swap(size, other.size);
       return *this;
   }  // other is destroyed here, freeing old memory
};

Why does operator= take the parameter by value instead of by const reference?

Need Help? Refer to the Quick Guide below

Select Answer