O'Reilly logo

C++ Primer, Fifth Edition by Barbara E. Moo, Josée Lajoie, Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required