13.2.1. Classes That Act Like Values


To provide valuelike behavior, each object has to have its own copy of the resource that the class manages. That means each HasPtr object must have its own copy of the string to which ps points. To implement valuelike behavior HasPtr needs

• A copy constructor that copies the string, not just the pointer

• A destructor to free the string

• A copy-assignment operator to free the object’s existing string and copy the string from its right-hand operand

The valuelike version of HasPtr is

class HasPtr {public:    HasPtr(const std::string &s = std::string()):        ps(new std::string(s)), i(0) { }    // each

Get C++ Primer, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.