The cost of passing by shared_ptr

前端 未结 5 1362
迷失自我
迷失自我 2020-12-07 09:35

I use std::tr1::shared_ptr extensively throughout my application. This includes passing objects in as function arguments. Consider the following:

class Datas         


        
5条回答
  •  心在旅途
    2020-12-07 10:18

    Always pass your shared_ptr by const reference:

    void f(const shared_ptr& pds) {...} 
    void g(const shared_ptr& pds) {...} 
    

    Edit: Regarding the safety issues mentioned by others:

    • When using shared_ptr heavily throughout an application, passing by value will take up a tremendous amount of time (I've seen it go 50+%).
    • Use const T& instead of const shared_ptr& when the argument shall not be null.
    • Using const shared_ptr& is safer than const T* when performance is an issue.

提交回复
热议问题