best practice when returning smart pointers

前端 未结 9 1396
一生所求
一生所求 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.

    0 讨论(0)
  • I follow the following guidelines for passing pointers arguments to functions and returning pointers:

    boost::shared_ptr
    

    API and client are sharing ownership of this object. However you have to be careful to avoid circular references with shared_ptr, if the objects represent some kind of graph. I try to limit my use of shared_ptr for this reason.

    boost::weak_ptr / raw pointer
    

    API owns this object, you are allowed share it while it is valid. If there is a chance the client will live longer than the api I use a weak_ptr.

    std::auto_ptr
    

    API is creating an object but the client owns the object. This ensures that the returning code is exception safe, and clearly states that ownership is being transferred.

    boost::scoped_ptr
    

    For pointers to objects stored on the stack or as class member variables. I try to use scoped_ptr first.

    Like all guidelines there will be times when the rules conflict or have to be bent, then I try to use intelligence.

    0 讨论(0)
  • 2020-12-24 12:38

    const boost::shared_ptr &getInternal() {return m_internal;}

    This avoids a copy.

    Sometimes you'll like to return a reference, for example:

    • Y &operator*() { return *m_internal; }
    • const Y &operator*() const { return *m_internal; }

    This is good too only if the reference will be used and discarded inmediately. The same goes for a raw pointer. Returning a weak_ptr is also an option.

    The 4 are good depending on the goals. This question requires a more extensive discussion.

    0 讨论(0)
提交回复
热议问题