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

前端 未结 3 915
暗喜
暗喜 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:42

    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.

提交回复
热议问题