1

While reading about smart pointers, especially in the case of std::shared_ptr & std::weak_ptr, I have often found people using the term "ownership" or "it owns the object". But what exactly is this ownership? It's even more confusing while trying to understand the use-case of std::weak_ptr!

If we write int a = 2 then can we say a owns 2? or

To be more specific, in int a = 2; int* ptr_a = &a;, can we say ptr_a owns a?

Milan
  • 1,743
  • 2
  • 13
  • 36
  • 1
    Ownership is usually used to define who is responsible for deleting dynamically allocated memory, so your `int` example doesn't fit this, since there is no dynamic allocation – UnholySheep Oct 28 '20 at 21:59
  • 2
    Does this help answer your question? [What is ownership of resources or pointers?](https://stackoverflow.com/questions/49024982/what-is-ownership-of-resources-or-pointers) – user4581301 Oct 28 '20 at 22:02
  • 1
    Because it's not covered in the above link, a `weak_ptr` is **not** an owner. It doesn't get any say in when the resource is released. What it gets is a way to test if the resource has been released and claim a (usually temporary) share of ownership if it hasn't been. – user4581301 Oct 28 '20 at 22:06

1 Answers1

4

In terms of smart pointers, ownership is the unit of code who has the authority on the lifetime of the object created on the memory.

If the lifetime of the object is shared between two places, that means the ownership is shared, unless both places agree to release/destroy the object, it won't be destructed.

If owner ship is single, that unit of code can determine when to destroy the object, all the other referrer code can only acquire a weak pointer, they cannot keep the object alive, only know that it was destructed or not.

Onur Onder
  • 306
  • 1
  • 4