Should I use shared_ptr or unique_ptr

前端 未结 4 1079
半阙折子戏
半阙折子戏 2020-11-30 03:29

I\'ve been making some objects using the pimpl idiom, but I\'m not sure whether to use std::shared_ptr or std::unique_ptr.

I understand that std::unique_ptr

4条回答
  •  旧时难觅i
    2020-11-30 04:18

    When you use a shared_ptr (for example in a container, then look this up and return it by-value), you are not causing a copy of the object it points to, simply a copy of the pointer with a reference count.

    This means that if you modify the underlying object from multiple points, then you affect changes on the same instance. This is exactly what it is designed for, so not some anti-pattern!

    When passing a shared_ptr (as the comments say,) it's better to pass by const reference and copy (there by incrementing the reference count) where needed. As for return, case-by-case.

提交回复
热议问题