From: A Tour of C++ (Second edition)
13.2.1 unique_ptr and shared_ptr
Using make_shared() is not just more convenient than separately making an object using new and then passing it to a shared_ptr, it is also notably more efficient because it does not need a separate allocation for the use count that is essential in the implementation of a shared_ptr.
My question: How come shared_ptr does need to allocate memory for reference counting and make_shared() not? (Will it allocate it only once there are at least two references to the data?)
Probably irrelevant to the question:
Given unique_ptr and shared_ptr, we can implement a complete “no naked new” policy (§4.2.2) for many programs. However, these “smart pointers” are still conceptually pointers and therefore only my second choice for resource management – after containers and other types that manage their resources at a higher conceptual level.
In particular, shared_ptrs do not in themselves provide any rules for which of their owners can read and/or write the shared object.
Data races (§15.7) and other forms of confusion are not addressed simply by eliminating the resource management issues.
Where do we use “smart pointers” (such as unique_ptr) rather than resource handles with operations designed specifically for the resource (such as vector or thread)? Unsurprisingly, the answer is “when we need pointer semantics.”
When we share an object, we need pointers (or references) to refer to the shared object, so a shared_ptr becomes the obvious choice (unless there is an obvious single owner). When we refer to a polymorphic object in classical object-oriented code (§4.5), we need a pointer (or a reference) because we don’t know the exact type of the object referred to (or even its size), so a unique_ptr becomes the obvious choice.
A shared polymorphic object typically requires shared_ptrs.
We do not need to use a pointer to return a collection of objects from a function;
Aucun commentaire:
Enregistrer un commentaire