Express who owns an object
RAII associates resource ownership with object lifetime. A smart pointer manages a dynamically allocated object and releases it according to an ownership policy. Prefer an ordinary local object when dynamic allocation is unnecessary, unique_ptr for exclusive ownership, and shared_ptr only when shared ownership is genuinely needed.
Exclusive ownership with unique_ptr
#include
#include
#include
#include
int main() {
auto first = std::make_unique("C++ lesson");
auto second = std::move(first);
std::cout << (first == nullptr) << '\n';
std::cout << *second << '\n';
} Expected lines: 1 and C++ lesson. Ownership moves to second; the moved-from unique_ptr is empty. unique_ptr is not copyable. Its destructor deletes the owned object automatically when the owner leaves scope.
Shared ownership is a different promise
A shared_ptr keeps an object alive until the last owning shared_ptr releases it. Copying one creates another owner of the same object, not a deep copy of the object. Prefer make_shared for a straightforward shared allocation. Do not construct two unrelated shared_ptr control blocks from the same raw pointer: that can lead to double deletion.
Break cycles with weak_ptr
If two objects hold owning shared_ptr links to each other, their reference counts may never reach zero. A weak_ptr observes a shared-owned object without extending its lifetime. Call lock to obtain a temporary shared_ptr and test whether it is non-empty before use.
std::weak_ptr observer;
{
auto owner = std::make_shared("Practice");
observer = owner;
if (auto live = observer.lock()) std::cout << *live << '\n';
}
std::cout << observer.expired() << '\n'; Inside main with the necessary headers, this prints Practice then 1. After the scope ends, no owner remains.
Ownership is not thread safety for the target
Reference-count management does not make arbitrary simultaneous modifications of the pointed-to object safe. Shared mutable state still needs a synchronization design. A raw pointer obtained by get is borrowed; it must not outlive the owner and must not be independently deleted.
Exercises
- Store several unique_ptr objects in a vector and release the vector without any explicit delete.
- Try copying a unique_ptr, read the diagnostic, then move it when ownership transfer is intended.
- Draw a shared_ptr cycle and replace one ownership link with weak_ptr.
- Explain why a simple local std::string often needs no smart pointer at all.
हिन्दी संकेत: smart pointer चुनने से पहले ownership तय करें; shared_ptr हर pointer का default replacement नहीं है।