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

前端 未结 3 916
暗喜
暗喜 2021-02-05 13:08

I can\'t think of any situation where

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


would be preferred to

auto obj         


        
      
      
      
3条回答
  •  梦如初夏
    2021-02-05 13:37

    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.

提交回复
热议问题