1. Goals
Distinguish creating an object through a copy constructor from assigning an existing object.
Explain why copying a class containing
std::stringcan produce independent values.Recognize when copying a pointer only creates an alias and breaks ownership rules.
2. Prerequisites
You know constructors, destructors, RAII, pointers, and ownership.
This lesson uses std::string as a member that owns its contents. You do
not need to implement a dynamic allocation class, smart pointers, or moves.
3. Explanation
Notebook copy(original); creates a new object through a copy constructor.
Notebook copy = original; is also initialization, despite the =.
In contrast, assigned = original; is copy assignment, because
assigned already exists. Its state is assigned from the source object;
this does not begin a new lifetime for the destination.
If you had to declare them yourself for Notebook, common signatures are
Notebook(const Notebook& other) and
Notebook& operator=(const Notebook& other). The first constructs an object;
the second takes a source and returns a reference to the destination.
Neither needs to be written for this example: the compiler supplies the
appropriate operations because the class and its members support them.
Default copying handles each member according to its type. For
std::string title_, the destination string receives the same contents
but has an independent value: renaming the copy does not rename the
original. The string member manages its memory, including when assigned
new contents or destroyed. Notebook therefore needs no handwritten
destructor, copy constructor, or copy assignment operator. This follows
the Rule of Zero in the C++ Core Guidelines.
The Rule of Zero does not prohibit a constructor that accepts initial data.
Default copying does not mean recursively duplicating everything. For
a pointer member, the copied value is an address; the pointed-to object
is not automatically duplicated. sameView = view in the example produces
two pointers borrowing the same Notebook. Editing through either changes
the original object; neither pointer should be used to delete it.
sameView->rename(...) is shorthand for (*sameView).rename(...): it calls
a member function on the pointed-to object. The pointer must be valid and
the object must still be alive during the call.
If an older class stores an int* obtained from new and its destructor
calls delete, copying that address gives two objects responsibility for
deleting one allocation. A destructor alone is insufficient. The Rule
of Three asks you to consider the destructor, copy constructor, and copy
assignment together: either copy the resource correctly or prohibit
invalid copying with = delete. Prefer an owning member such as
std::string when it fits the task instead of writing all three yourself.
The C++11 track covers moving resources in more detail.
After Foundation, continue with Copy constructor
and Copy assignment and the Rule of Three
to see how these copying operations can be defined explicitly.
title() returns const std::string&: callers borrow the string member;
they do not receive a copy or extend the notebook's lifetime. If the title
must survive the notebook, use std::string saved = original.title(); to
copy its value. Choose a reference or a copy based on lifetime and editing
needs, rather than assuming all copies are too expensive.
4. Runnable example
Save as main.cpp, compile as C++17, and run; no input is needed.
#include <iostream>
#include <string>
class Notebook {
public:
explicit Notebook(const std::string& title) : title_(title) {}
void rename(const std::string& title) {
title_ = title;
}
const std::string& title() const {
return title_;
}
private:
std::string title_;
};
int main() {
Notebook original("C++ notes");
Notebook copy(original);
Notebook assigned("Old draft");
assigned = original;
copy.rename("Exercises");
assigned.rename("Revision");
std::cout << "Original: " << original.title() << '\n';
std::cout << "Copy: " << copy.title() << '\n';
std::cout << "Assigned: " << assigned.title() << '\n';
Notebook* view = &original;
Notebook* sameView = view;
sameView->rename("Shared edit");
std::cout << std::boolalpha;
std::cout << "Same object: " << (view == sameView) << '\n';
std::cout << "Original after borrowed edit: " << original.title() << '\n';
std::cout << "Copy after borrowed edit: " << copy.title() << '\n';
std::cout << "Assigned after borrowed edit: " << assigned.title() << '\n';
return 0;
}Output:
Original: C++ notes
Copy: Exercises
Assigned: Revision
Same object: true
Original after borrowed edit: Shared edit
Copy after borrowed edit: Exercises
Assigned after borrowed edit: Revision5. Common mistakes
Calling
=in a declaration assignment to an existing object.Assuming a copy constructor duplicates every object reached through pointer members.
Adding a destructor that calls
deletewhile copies still own the same address.Writing special member functions when members already manage their resources correctly.
Keeping the reference returned by
title()beyond the notebook's lifetime, or deleting a borrowed pointer.
6. Practice
Replace
Notebook copy(original);withNotebook copy = original;. Output must remain unchanged: this still constructs a new copy.Add
Notebook another("Temporary");followed byanother = copy;. Renamecopyafterward:anothermust retain the title it received during assignment.Create
Notebook& same = original;and then executeoriginal = same;. This is self-assignment through an alias; the title must remain intact. With astd::stringmember as used here, no custom check is needed.Keep
std::string saved;outside a block, create a notebook inside, and assignsaved = notebook.title();. Printingsavedafter the block must still show the correct contents. Do not replace it with a reference to the notebook whose lifetime has ended.
7. Self-check
Which line uses a copy constructor, and which uses copy assignment? Answer:
Notebook copy(original);creates a new object and uses a copy constructor.assigned = original;changes an existing object's state and uses copy assignment. An=in a declaration is still initialization.Why does
copy.rename(...)leaveoriginalunchanged, whilesameView->rename(...)changes it? Answer:copycontains an independent string value.sameViewonly copied the address oforiginal, so editing through it directly changes the original object.Which functions should a class that deletes an owning pointer consider? Answer: its destructor, copy constructor, and copy assignment operator. Define safe resource copying or prohibit copying. If a suitable owning member is available, prefer the Rule of Zero to doing this yourself.
Sample code
Source file
cpp98_foundation/16_copy_assignment/main.cpp
#include <iostream>
#include <string>
class Notebook {
public:
explicit Notebook(const std::string& title) : title_(title) {}
void rename(const std::string& title) {
title_ = title;
}
const std::string& title() const {
return title_;
}
private:
std::string title_;
};
int main() {
Notebook original("C++ notes");
Notebook copy(original);
Notebook assigned("Old draft");
assigned = original;
copy.rename("Exercises");
assigned.rename("Revision");
std::cout << "Original: " << original.title() << '\n';
std::cout << "Copy: " << copy.title() << '\n';
std::cout << "Assigned: " << assigned.title() << '\n';
Notebook* view = &original;
Notebook* sameView = view;
sameView->rename("Shared edit");
std::cout << std::boolalpha;
std::cout << "Same object: " << (view == sameView) << '\n';
std::cout << "Original after borrowed edit: " << original.title() << '\n';
std::cout << "Copy after borrowed edit: " << copy.title() << '\n';
std::cout << "Assigned after borrowed edit: " << assigned.title() << '\n';
return 0;
}