简体   繁体   中英

Is there any reason not to use std::make_shared when constructing objects?

I can't think of any situation where

std::shared_ptr<Object> obj(new Object("foo", 1));

would be preferred to

auto obj = std::make_shared<Object>("foo", 1);

The latter always results in better locality and reduces memory fragmentation. Is there any situation, where you would prefer (or be forced) to use the first form, except interfacing with code returning raw pointers?

The latter always results in better locality and reduces memory fragmentation.

Not always . An implementation is encouraged to use a single allocation for the reference counted object and the reference count, but it is not required to do so.

Why might you not want to use std::make_shared ? Consider the case where you have a large dynamically allocated object that you want owned by std::shared_ptr and you know that there will be weak references to this object that are likely to outlive the strong references to the object (perhaps there are many weak references and only one or two short-lived strong references).

In this case, std::make_shared would be a poor choice, assuming it allocates a single block that owns both the object and the reference count: the allocated block (which is large, remember) cannot be destroyed until there are no strong or weak references left to the object.

If you were to dynamically allocate the object yourself and pass the pointer to the std::shared_ptr constructor, the memory occupied by the object could be released as soon as there are no strong references remaining, even if there are still weak references.

Modern IDEs have "Find usages" feature. If you use std::make_shared to construct the object, when you search for the places where the constructor of that object is called, IDE won't show up the places where std::make_shared is used.

If you are constructing an object that will have multiple entities sharing in the lifetime of the object, then yes, you want to prefer to use std::make_shared where possible. Some places it might not be possible is if you obtain the pointer from someone else; for example, a factory might return a raw pointer or a std::unique_ptr that you would like to store in a shared_ptr, thus preventing use of make_shared.

The question in the title is a bit different; there are plenty of reasons you might not want to use shared_ptr for your objects at all. You should only use shared_ptr if the lifetime is actually shared by multiple objects. Otherwise, prefer stack allocating the object or using unique_ptr.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM