Shared Pointer
As we saw, unique pointer are one-to-one mapped. Meaning, one pointer variable can only stored by one unique_prt
and it cannot be referenced by any other unique pointer. A unique pointer will free the referenced memory as soon as this unique_ptr
goes out of scope.
A shared_ptr
is different from that, here you can create multiple wrappers that are refer to same pointer, memory will be freed once all the shared_ptr
goes out of scope.
Shared pointers are a type of smart pointer introduced in C++11 that provide automatic memory management through reference counting. Here's a concise overview:
Shared pointers (std::shared_ptr
) allow multiple pointers to share ownership of a dynamically allocated object. Key points:
Automatic memory management: The object is automatically deleted when the last shared pointer owning it is destroyed.
Reference counting: Internally maintains a count of how many shared pointers are pointing to the object.
Thread-safe reference count: The reference count is incremented and decremented in a thread-safe manner.
Overhead: Slight performance overhead due to reference counting.
Cyclic references: Can lead to memory leaks if not handled properly (use weak_ptr to break cycles).
Last updated