C++ Pointers

I've been brushing up on my lacking C++ skills and am reading Scott Meyers Effective Modern C++.

In the chapter about smart pointers, there is this discussion on converting smart pointers:

In exchange for these rather modest costs, you get automatic lifetime management of dynamically allocated resources. Most of the time, using std::shared_ptr is vastly preferable to trying to manage the lifetime of an object with shared ownership by hand. If you find yourself doubting whether you can afford use of std::shared_ptr, reconsider whether you really need shared ownership. If exclusive ownership will do or even may do, std::unique_ptr is a better choice. Its performance profile is close to that for raw pointers, and “upgrading” from std::unique_ptr to std::shared_ptr is easy, because a std::shared_ptr can be created from a std::unique_ptr.

The reverse is not true. Once you’ve turned lifetime management of a resource over to a std::shared_ptr, there’s no changing your mind. Even if the reference count is one, you can’t reclaim ownership of the resource in order to, say, have a std::unique_ptr manage it. The ownership contract between a resource and the std::shared_ptrs that point to it is of the ’til-death-do-us-part variety. No divorce, no annulment, no dispensations.

I understand the concept of converting a unique_ptr to a shared_ptr, but I'm a bit lost as to why the converse in invalid. If you had a unique_ptr that was converted to a shared_ptr, and for whatever reason, needed to convert it back to a unique_ptr, would you not be able to create a new unique_ptr with reference/copy to the shared_ptr?

submitted by /u/kkirch
[link] [comments]

from Software Development – methodologies, techniques, and tools. Covering Agile, RUP, Waterfall + more! http://bit.ly/2UDuSvi

Leave a comment

Design a site like this with WordPress.com
Get started
search previous next tag category expand menu location phone mail time cart zoom edit close