C++20 sections · 1024 units
Open in Course

What is unique_ptr?

Single owner

unique_ptr owns its resource exclusively. Only one unique_ptr can point to a given object at a time. When the unique_ptr is destroyed, it deletes the object. No manual delete needed. You can't copy a unique_ptr because that would create two owners.

But you can move it with std::move, transferring ownership from one unique_ptr to another. Use unique_ptr as your default smart pointer. It has zero overhead compared to raw pointers.

The compiler generates the same code but with guaranteed cleanup.