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/W_2ovphV
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
exercise1folder of your GitHub repository edit the filemain.cppand create aunique_ptrto 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
printBoxValuea 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.mdfile, 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
exercise2folder of your GitHub repository edit the filemain.cppand create aunique_ptrmanaging aBoxobject. - Implement the
createBoxWithValuefunction that returns a unique_ptr. - Implement the
transferOwnershipfunction to transfer ownership of theBoxobject from oneunique_ptrto another. - In the
README.mdfile, 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_ptrinstances are created and destroyed. - In the
README.mdfile, 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.mdfile, 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_ptris gone.