best practice when returning smart pointers

前端 未结 9 1433
一生所求
一生所求 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:25

    I typically return "owning"/"unique" smart pointers from factories or similar to make it clear who is responsible for cleaning up.

    This example https://ideone.com/qJnzva shows how to return a std::unique_ptr that will be deleted when the scope of the variable that the caller assigns the value to goes out of scope.

    While it's true that the smart pointer deletes its own pointer, the lifetime of the variable holding the smart pointer is 100% controlled by the caller, so the caller decides when the pointer is deleted. However, since it's a "unique" and "owning" smart pointer, no other client can control the lifetime.

提交回复
热议问题