What is a shared_ptr?

Asked

Viewed 459 times

5

If possible, with an example of code, as this is missing in the reference to really understand when and how to use the shared_ptr.

1 answer

5


You use it when you want to create a pointer to an object and let C++ manage it for you. The object will be automatically destroyed when there are no more references to it.

It is preferable to use the unique_ptr where possible. The shared_ptr uses a reference counter to control whether it still needs to be active. In addition to the memory cost to store the counter it is necessary to increment this counter every time it creates a new reference and decrement and check if it has reached zero when a reference to the object is abandoned. This may not be so cheap in some scenarios. It gets worse if you have to synchronize the increment/decrease in a competitive environment. The unique_ptr has no cost (neither memory, nor processing, even zero), but can only have a reference to the object, which is the most common that occurs.

Both do not eliminate the cost of allocating heap, only ensure that an object is not released before, nor after the moment that it actually has no more use.

It is a form of garbage collector, although not traditional as some know and so has other commitments, advantages and disadvantages.

Documentation.

Has a example here.

  • For more than one reference to an object, do you refer to the situation that when, for example, if passed as parameter it has a copy that changes are not applied at source? (when the passage is not by reference)

  • On the contrary, what you are saying are references to distinct objects. The shared_ptr serves for the same object. What a reference changes in the object, the others will see the change.

  • I don’t know exactly why, but it reminded me of DCOM and its famous smart pointers with CComPtr (God protect me... in the name of the Father, the Son and the Holy Spirit, amen).

  • 1

    @Luizvieira You know you’re different :)

  • Yes, of course. But it reminded me of that bizarre Microsoft thing (and gave me a chills here rs).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.