How to release pointer from boost::shared_ptr?

后端 未结 14 1631
刺人心
刺人心 2020-11-30 06:42

Can boost::shared_ptr release the stored pointer without deleting it?

I can see no release function exists in the documentation, also in the FAQ is explained why it

14条回答
  •  青春惊慌失措
    2020-11-30 06:57

    To let the pointer point to nothing again, you can call shared_ptr::reset().

    However, this will delete the object pointed to when your pointer is the last reference to the object. This, however, is exactly the desired behaviour of the smart pointer in the first place.

    If you just want a reference that does not hold the object alive, you can create a boost::weak_ptr (see boost documentation). A weak_ptr holds a reference to the object but does not add to the reference count, so the object gets deleted when only weak references exist.

提交回复
热议问题