Home | Projects | Notes > C++ Programming > Smart Pointers

Smart Pointers

 

Overview

 

Issues with Raw Pointers

 

What is Smart Pointer? (Ownership & RAII)

RAII - Resource Acquisition Is Initialization

 

C++ Smart Pointers

Unique Pointers (unique_ptr)

Shared pointers (shared_ptr)

Weak Pointers (weak_ptr)

 

 

Custom Deleters

Providing Custom Deleters through Functions

You can write a custom deleter function that will be called automatically when the smart pointer is destroyed. This function receives a raw pointer to the managed object that the smart pointer owns. Inside this function, perform whatever steps are necessary to properly release your resources.

L7: The second argument of the initializer list is the name of the custom deleter function.

L1: ptr is a raw pointer to the Test object.

Providing Custom Deleters through Lambdas

A lambda is an anonymous function, meaning it has no name, and can be defined inline exactly where you need to use it. This eliminates the need to write a separate, named function elsewhere in the code.

L1: The Lambda will be called when the ptr is destroyed.

 

Final Thoughts

There are many opinions about when to use different types of smart pointers. The answer is: it depends.