13.2.1. Classes That Act Like Values

Image

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.