std::unique_ptr
is a smart pointer with unique ownership semantics.// Always use make_unique() to create a unique_ptr void processData(Simple* simple) {} auto smartPtr = make_unique<Simple>(); processData(smartPtr.get()); // call get() to get the underlying pointer smartPtr.reset(); // Free resource and set to nullptr smartPtr.reset(new Simple()); // free resource and set to a new smartPtr.release() // return the underlying pointer to the resource and then set the smart pointer to nullptr.
unique_ptr
represents unique ownership, it cannot be copied . Usingstd::move()
to explicitly move ownership.
You can offer custom deleter. It is useful to manage other resources instead of just memory.int* malloc_int(int value) { int* p = (int*)malloc(sizeof(int)); *p = value; return p; } int main() { // The template type parameter should be the type of a pointer to a function, // so an additional * is appended, as in decltype(free)* unique_ptr<int, decltype(free)*> myIntSmartPtr(malloc_int(42), free); return 0; }
std::shared_ptr
is a smart pointer with shared ownership semantics using reference counting .// Always use make_shared() to create a shared_ptr. auto smpt = make_shared<Simple>(); // Also support the get() and reset() methods, when calling reset(), due to reference counting, // the underlying resource is only freed when the last shared_ptr is destroyed or reset. // Not support release(), you can use use_count() to retrieve the number of shared_ptr instances that are sharing the same resource.
std::weak_ptr
, contains a reference to a resource managed by ashared_ptr
.weak_ptr
does not own the resource, so theshared_ptr
is not prevented from deallocating the resource.weak_ptr
does not destroy the pointed-to resource when the it is destroyed.- The constructor of a
weak_ptr
required ashared_ptr
or anotherweak_ptr
as argument. - To get access to the pointer stored in a
weak_ptr
, you need to convert it to ashared_ptr
:- Use the
lock()
method on aweak_ptr
instance, which returns ashared_ptr
. The returnedshared_ptr
isnullptr
if theshared_ptr
associated with theweak_ptr
has been deallocated. - Create a new
shared_ptr
instance and give aweak_ptr
as argument to theshared_ptr
constructor.
- Use the