Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 1.66 KB

smart_ptr.md

File metadata and controls

45 lines (39 loc) · 1.66 KB

Smart Pointers in C++

Smart pointers are types which manage a raw pointer in their constructors and destructors. This way, you don't have to use new/delete manually, which is easy to forget and hard to do correctly, especially when handling exceptions.

std::unique_ptr

?inline

std::shared_ptr

?inline

std::weak_ptr

?inline

  • non-owning
  • constructed from std::shared_ptr
  • converted to std::shared_ptr when accessing managed object

Specializations for Arrays

std::unique_ptr and std::shared_ptr have specializations for array types (since C++11, C++17 respectively). For example:

// Make unique array of 100 ints.
// In practice, use auto = ...;
std::unique_ptr<int[]> =
    std::make_unique<int[]>(100);

Relevant Links

<:cppreference:875716540929015908> std::unique_ptr, std::shared_ptr, std::weak_ptr
<:stackoverflow:874353689031233606> What is a smart pointer and when should I use one?
<:cppreference:875716540929015908> Smart Pointer Casts
<:cppreference:875716540929015908> Standard library header