std::unique_ptris 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_ptrrepresents 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_ptris 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_ptrdoes not own the resource, so theshared_ptris not prevented from deallocating the resource.weak_ptrdoes not destroy the pointed-to resource when the it is destroyed.- The constructor of a
weak_ptrrequired ashared_ptror anotherweak_ptras 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_ptrinstance, which returns ashared_ptr. The returnedshared_ptrisnullptrif theshared_ptrassociated with theweak_ptrhas been deallocated. - Create a new
shared_ptrinstance and give aweak_ptras argument to theshared_ptrconstructor.
- Use the