Brief overview of smart pointers

A smart pointer is a templated class that wraps a traditional/raw pointer and handles deletion. They are typically used for high-level program logic, not for low-level data structures such as a linked list. To use smart pointers include the library: #include

shared_ptr

A shared_ptr can point to more than one object at a time. It will maintain a reference counter (uses use_count() method) so garbage collection can happen. When the reference counter is zero, the object is deleted.

weak_ptr

A weak_ptr is similar to a shared_ptr except it will not maintain a reference counter. The main reason for using weak_ptrs is to handle circular dependence. For example, if a Course object held shared_ptrs to Student objects and Student objects held shared_ptrs to the Course object, there would be no way for the reference counter to get to zero. So, let the Course hold shared_ptrs to Student objects and Student objects hold weak_ptrs to the Course object.

unique_ptr

A unique_ptr points to an object that no other pointer points to. A different object can be assigned to a unique_ptr by removing another pointer to it. These are primarily used with threads (Operating Systems) and are not used in CSS 342.