What is a shared_ptr?

5

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

    
asked by anonymous 16.02.2016 / 17:23

1 answer

5

You use it when you want to create a pointer to some 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 unique_ptr whenever possible. shared_ptr uses a reference counter to control whether it still needs to be active. In addition to the cost of memory to store the counter, it is necessary to increment this counter every time it has a new reference and decrement and check if it 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 / decrement 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 occurrence.

Documentation .

You have a example here .

    
16.02.2016 / 17:51