When to use unique_ptr

Hello. I have recently learned about unique_ptr and I wonder when I should use it over the original way (Deleting them yourself).
You should use unique_ptr when writing the component that would otherwise be solely responsible for delete-ing the resource manually. unique_ptr represents this responsibility to say delete: that is, it represents sole ownership of a resource.

- If a component is not responsible at all for releasing the resource (because, e.g., it only wants to examine that resource), one would use normal old ("raw") pointers.

- If a component is solely responsible for releasing a resource (because e.g., that resource is useless without the component), one would use std::unique_ptr

- If a component shares responsibility for releasing a held resource (because, e.g., that resource is shared between threads of execution), then one would reach for std::shared_ptr and std::weak_ptr, but this is rare, and should be avoided.

See this S/O question:
https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one

Edit:
After re-reading it, I wouldn't recommend that S/O question any more. It is too out-of-date, and recommends practices that aren't idiomatic any more.

The current best practice is quite well summarized in the Core Guidelines:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r-resource-management
Last edited on
Topic archived. No new replies allowed.