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

放肆的年华 提交于 2019-11-27 10:27:39

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.

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.

ltjax

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!