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.
?inline
- unique ownership
- not copyable, only movable
- use with std::make_unique
?inline
- shared ownership
- copyable (thread-safely)
- use with std::make_shared
?inline
- non-owning
- constructed from
std::shared_ptr
- converted to
std::shared_ptr
when accessing managed object
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);
<: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