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

后端 未结 3 1533
误落风尘
误落风尘 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:40

    Use a shared_ptr when you require multiple things own a resource (and those owning things may go in and out of scope at "random"), use a unique_ptr when a single thing owns the resource, and use a raw pointer when you just need to refer to it and not own it (and expect this referral to not last longer than the resource exists).

    There is a fourth type, a sort of raw-pointer-for-shared_ptr's, called weak_ptr. You use that to refer to a shared_ptr without actually owning it; you can then check if the object is still there and use it.

提交回复
热议问题