Module 14: C++ Smart Pointers
- First read this page then start the module with the GitHub classroom link below.
- Github Classroom Link: https://classroom.github.com/a/0cDkb2CT
Exercise 1: Basic Usage of unique_ptr
Understand the basic mechanics of unique_ptr
and how it manages the lifecycle of a heap-allocated object.
- In the
exercise1
folder of your GitHub repository edit the filemain.cpp
and create aunique_ptr
to manage a dynamically allocated object of a simple classBox
. The Box class has one integer member variable and a constructor that sets it. - Implement the
printBoxValue
a function that takes aunique_ptr<Box>
by value and prints the value of theBox
’s member variable. - Demonstrate what happens when you try to copy the
unique_ptr
. - In the
README.md
file, explain why it is not allowed.
Exercise 2: Transfer of Ownership with unique_ptr
Learn how to transfer ownership of managed objects with unique_ptr
.
- In the
exercise2
folder of your GitHub repository edit the filemain.cpp
and create aunique_ptr
managing aBox
object. - Implement the
createBoxWithValue
function that returns a unique_ptr. - Implement the
transferOwnership
function to transfer ownership of theBox
object from oneunique_ptr
to another. - In the
README.md
file, explain how the transfer of ownership works.
Exercise 3: Introduction to shared_ptr
Familiarize with the basics of shared_ptr
and reference counting.
- Create several
shared_ptr<Box>
instances that all manage the same Box object. - Print the reference count of these shared pointers.
cout << "Reference count: " << sharedSmartPointer.use_count() << endl;
- Demonstrate how the reference count changes as
shared_ptr
instances are created and destroyed. - In the
README.md
file, explain the different ways to create and destroy ashared_ptr
.
Exercise 4: Sharing and Releasing with shared_ptr
Learn how shared_ptr
allows multiple owners and how to release ownership correctly.
- Create a
shared_ptr<Box>
and another one that shares ownership with the first one. - Implement a function that takes a
shared_ptr<Box>
by value and another one by reference. - Demonstrate how passing by value and by reference to functions affects the reference count.
- In the
README.md
file, explain why passing by value and by reference to functions affects the reference count differently. - Use
.reset()
to release ownership and observe how the object is only destroyed when the lastshared_ptr
is gone.