C++11: Replace all non-owning raw pointers with std::shared_ptr()?

后端 未结 3 1505
误落风尘
误落风尘 2020-12-02 06:03

With the advent of std::unique_ptr, the blemished std::auto_ptr can finally be put to rest. So for the last several days, I have been changing my

3条回答
  •  粉色の甜心
    2020-12-02 06:54

    The only non-owning smart-pointer in the standard library is std::weak_ptr. However, to use it, the actual owning object needs to hold the pointee in a std::shared_ptr.

    I assume you used std::unique_ptr on those before. If you convert them to shared_ptr now, you'll have the benefit that your non-owning pointers can know that the owning pointer lost is reference while raw pointers can be left dangling without any chance for the non-owning component to detect this. However, shared_ptr will incur a (very?) small performance and memory overhead over unique_ptr.

    Personally, I recommend using one shared_ptr and many weak_ptrs instead of one unique_ptr and many raw-pointers in the general case and use unique_ptr if you really have a performance problem!

提交回复
热议问题