Getting a boost::shared_ptr for this

前端 未结 6 2045
有刺的猬
有刺的猬 2020-12-02 07:11

I am making extensive use of boost:shared_ptr in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr. Unf

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 07:39

    Just use a raw pointer for your function parameter instead of the shared_ptr. The purpose of a smart pointer is to control the lifetime of the object, but the object lifetime is already guaranteed by C++ scoping rules: it will exist for at least as long as the end of your function. That is, the calling code can't possibly delete the object before your function returns; thus the safety of a "dumb" pointer is guaranteed, as long as you don't try to delete the object inside your function.

    The only time you need to pass a shared_ptr into a function is when you want to pass ownership of the object to the function, or want the function to make a copy of the pointer.

提交回复
热议问题