Disadvantages of shared_ptr

前端 未结 3 619
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 07:49

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:24

    Of course there are disadvantages: you require extra memory to maintain a reference count, and every time you copy or destroy a shared_ptr instance this reference count has to be incremented and decremented. If your program uses multiple threads then the manipulation of the reference count has to be done in a thread-safe manner, which can add some additional overhead, the magnitude of which depends on the implementation.

    Whether or not this overhead impacts your program in an overall negative way depends on the details of your program. Generally you should only use std::shared_ptr for resources that truly need to be shared, because it can be somewhat arbitrary which object will need them last. In other cases, a single point of ownership is usually easier to maintain because you know exactly how long each resource will be alive.

    Additionally, you need to be aware that std::shared_ptr is not a panacea for object lifetime management. In particular, if you have two objects that each own an std::shared_ptr to the other, the objects have cyclic ownership and will never be automatically deleted unless you first break the cycle by invoking reset() on one of them.

提交回复
热议问题