Deep copy semantics create independent copies of dynamically owned resources instead of copying pointers that make source and target share the same memory. Shallow copying can violate the class invariant and cause incorrect behavior when ownership is meant to remain unique. section 8.6
A class owning dynamic resources must coordinate its destructor, copy constructor, and copy assignment operator. The copy constructor creates a new resource from the source; assignment first handles the target’s existing resource, then creates its independent copy. Modern C++ extends this responsibility with move construction and move assignment. section 7.6
The copied Page shares its body
A problematic Page copies body(o.body), so two Page objects refer to one TextSection. The corrected copy constructor uses new TextSection(*(o.body)); copy assignment deletes the existing body before allocating its independent copy, and the destructor releases it. A modernized version uses std::unique_ptr and defaulted move operations. section 7.6
Listing 7.7 A copy constructor that shares unique resources
class TextSection {
// assume a clever implementation
};
class Page {
private:
TextSection* headers; #1
TextSection* body;
public:
Page(TextSection* h) : headers(h), body(new TextSection()) {}
Page(const Page& o) : headers(o.headers), body(o.body) {} #2
Page& operator=(const Page&);
};
int main() {
Page p1(new TextSection());
Page p2 = p1;
return 0;
}
Compare the sharing copy constructor with the uniqueness-preserving implementation in the corrected listing. section 7.6
Deep copying is not always the right ownership operation. A unique resource, such as a limited printer or an endpoint-bound communication channel, may need transfer rather than duplication; after transfer, the source no longer owns or uses it. section 8.6




