Explicitly deleting a shared_ptr

前端 未结 5 1814
遇见更好的自我
遇见更好的自我 2021-02-01 16:37

Simple question here: are you allowed to explicitly delete a boost::shared_ptr yourself? Should you ever?

Clarifying, I don\'t mean delete the pointer held

5条回答
  •  甜味超标
    2021-02-01 17:11

    [Edit: you can delete a shared_ptr if and only if it was created with new, same as any other type. I can't think why you'd create a shared_ptr with new, but there's nothing stopping you.]

    Well, you could write delete ptr.get();.

    Doing so leads almost inevitably to undefined behavior either when the other shared owners use their shared_ptr to access the now-deleted object, or the last shared_ptr to the object is destroyed, and the object gets deleted again.

    So no, you shouldn't.

    The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.

提交回复
热议问题