Learn C++ Online

Implementing a shared pointer

On this page
This lesson contains approximately 16 minutes of video content.

A naive implementation of a std::shared_ptr<T>

Note: In the interest of time, I did not implement the copy assignment operator for the shared pointer defined in this video.

Questions

Q1

QShared Pointers, Q1

This question is ungraded.

You are implementing a simple program managing extracurricular club rosters and participating students using smart pointers. Clubs and students both reside in the free store. Each club will have a std::vector storing pointers to its student members and each student will have a std::vector storing pointers back to the clubs to which they belong to.

A club will have many student members and a student can belong to many clubs. A club can remove a student from its rosters for inactivity without notifying the student. A student is no longer considered a participant when they belong to zero clubs, and have their memory automatically deallocated at this time. To accomplish this desired behavior, a club's student std::vector elements should be typed:

Q2

QShared Pointers, Q2

This question is ungraded.

We use a shared pointer to share ownership of a dynamically allocated object. To do this, we maintain a reference count across all the shared pointer objects involved in the shared ownership. The dynamically allocated object is deallocated from memory once all the shared pointers pointing to it have been destructed.

How can we effectively maintain a reference count that is mutually accessible amongst all the shared pointers engaged in the shared ownership of an object?