title: Implementing valuelike copy-assignment operator
body: <p>In C++ Primer there is an example of using the copy-control members to make a class act "valuelike"; that is, when copying the object, the copies are independent. It proposes the following code:</p>
  
  <pre><code>class HasPtrValue
  {
  public:
      HasPtrValue(const std::string &amp;s = std::string()) : ps(new std::string(s)), i(0) {  }
      HasPtrValue(const HasPtrValue &amp;orig) : ps(new std::string(*orig.ps)), i(orig.i) { }
      HasPtrValue&amp; operator=(const HasPtrValue&amp;);
      ~HasPtrValue() { delete ps; };
  
      std::string *ps;
      int i;
  };
  
  HasPtrValue&amp; HasPtrValue::operator=(const HasPtrValue &amp;rhs)
  {
      auto newp = new std::string(*rhs.ps);
      delete ps;
      ps = newp;
      i = rhs.i;
      return *this;
  }
  </code></pre>
  
  <p>My question is regarding the copy-assignment operator. As I understand what it does is create a new string on the heap, delete the old one, and make the lhs point to the new one. Is that really necessary? Will the below code not do exactly the same thing by simply assigning to the existing string on the heap?</p>
  
  <pre><code>HasPtrValue&amp; HasPtrValue::operator=(const HasPtrValue &amp;rhs)
  {
      *ps = *rhs.ps;
      i = rhs.i;
      return *this;
  }
  </code></pre>