best practice when returning smart pointers

前端 未结 9 1434
一生所求
一生所求 2020-12-24 11:56

What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I co

9条回答
  •  一整个雨季
    2020-12-24 12:34

    It depends on what the meaning of the pointer is.

    When returning a shared_pointer, you are syntactically saying "You will share ownership of this object", such that, if the the original container object dies before you release your pointer, that object will still exist.

    Returning a raw pointer says: "You know about this object, but don't own it". It's a way of passing control, but not keeping the lifetime tied to the original owner.

    (in some older c-programs, it means "It's now your problem to delete me", but I'd heavily recommend avoiding this one)

    Typically, defaulting to shared saves me a lot of hassle, but it depends on your design.

提交回复
热议问题