C++ Smart Pointer: unique vs shared

Introduction

The main differences between unique and shared pointers are:

  • With unique pointers, we have one pointer pointing at and owning a single object
  • With shared pointers, we have multiple pointers pointing at and owning a single object.
  • Unique pointers can not be copied, whereas shared pointers can.

90% of the time, you will be using the unique pointer.

Shared pointers can be used to represent data structures such as graphs.

Smart pointers are class templates themselves, meaning they have member functions.

With smart pointers, we do not need to specify the <some_type*>, we just need to specify the <some_type>.

Prefer smart pointers to raw pointers.




PreviousNext

Related