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

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

    Personally, this is how I (more or less) do it:

    • unique_ptrs are for sole ownership
    • raw pointers mean whoever gave me the raw pointer guarantees the lifetime of that object to match or exceed my lifetime.
    • shared_ptrs are for shared ownership
    • weak_ptrs are for when a system wants to check if the object still exists before using it. This is rare in my code since I find it cleaner to have a system guarantee the lifetime of anything it passes it's subsystems (in which case I use a raw pointer)

    By far I use more unique_ptrs than shared_ptrs, and more raw pointers than weak pointers.

提交回复
热议问题