Disadvantages of shared_ptr

前端 未结 3 932
粉色の甜心
粉色の甜心 2021-02-14 08:15

With shared_ptr included in c++11, one could achieve a semi garbage-collected enviroment. Does the (inflationary?) usage come along with some disadvantages?

I could imag

3条回答
  •  遇见更好的自我
    2021-02-14 08:33

    One other thing worth mentioning is that you need to be very careful when designing your APIs with std::shared_ptr.

    The obvious advantage over a raw pointer is the automatic memory management (with the cyclic ownership gotcha) but other problems/questions remain. When the resource is shared, you're giving up (to some extent) control and the ability to reason about your code.

    Can I modify the object given that I might not be the only one holding onto it?

    You change the object and the change reflects to the whole system. The larger the system, the less obvious are the implications and it's harder to prove that it's in fact safe to do. Sean Parent often says that a shared ptr is in fact as good as a global variable.

提交回复
热议问题