c++unique-ptrownership-semantics

What does it mean to have sole ownership of object for unique_ptr?


I know that std::unique_ptr is used when an object has only one owner and std::shared_ptr is used when an object has multiple owners. What does it mean to be the unique owner of an object?

Does being the unique owner mean that nobody else gets to see the object?

Can I return the raw pointer using the get() method when passing the pointer as a reference?

I feel that if I have to use get(), then I have either transfer ownership by using std::move, or use a shared pointer.


Solution

  • Ownership is all about: who cleans up the resource when it is no longer needed?

    To be the only owner of a resource means that only you are responsible for deleting the object when it is no longer needed. This implies that nobody else can use the object after your lifetime ended. If others depend on the object still being alive after your lifetime ended you need shared ownership.

    In modern C++, raw pointers should not participate in ownership. When you pass a raw pointer to a function you expect that this function will not hold on to this pointer to use it later.