Monday, 1 March 2021

Chapter 19 // Exercise 11 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2017 and a modified version of the std_lib_facilities header found here.

Chapter 19 // Exercise 11

Design and implement a counted_ptr<T> that is a type that holds a pointer to an object of type T and a pointer to a "use count" (an int) shared by all counted pointers to the same object of type T. The use count should hold the number of counted pointers pointing to a given T

Let the counted_ptr's constructor allocate a T object and use a count on the free store. Let counted_ptr's constructor take an argument to be used as the initial value of the T elements. When the last counted_ptr for a T is destroyed, counted_ptr's destructor should delete the T.

Give the counted_ptr operations that allow us to use it as a pointer. This is an example of a "smart pointer" used to ensure that an object doesn't get destroyed until after its last user has stopped using it. Write a set of test cases for counted_ptr using it as an argument in calls, container elements, etc.


So I think this is basically a shared pointer and it took me a moment to wrap my head around what to do. The main key things are to ensure we're not allocating when copying (or increasing if the pointers are pointing at the same thing) as well as only delete the object and counter once all the other shared pointers have gone out of scope.

No comments:

Post a Comment