Part 3/7:
To mitigate issues associated with raw pointers, C++ offers an elegant solution in the form of smart pointers. Smart pointers are mechanisms that manage the lifetime of an object through automatic memory management. C++ provides three types of smart pointers: unique_ptr
, shared_ptr
, and weak_ptr
, each designed to handle different ownership scenarios effectively.
Unique Pointers
The unique_ptr
is a smart pointer that provides exclusive ownership semantics. Only one unique_ptr
can point to a given object, ensuring that the object is automatically destroyed when the unique_ptr
goes out of scope. The following code snippet demonstrates the creation and manipulation of a unique_ptr
:
std::unique_ptr<Dog> dog = std::make_unique<Dog>();
dog->setName("Rex");