Passing const shared_ptr& versus just shared_ptr as parameter

前端 未结 6 1053
误落风尘
误落风尘 2021-02-02 09:11

I\'ve been reading quite a number of discussions about performance issues when smart pointers are involved in an application. One of the frequent recommendations is to pass a sm

6条回答
  •  忘掉有多难
    2021-02-02 09:58

    If no modification of ownership is involved in your method, there's no benefit for your method to take a shared_ptr by copy or by const reference, it pollutes the API and potentially incur overhead (if passing by copy)

    The clean way is to pass the underlying type by const ref or ref depending of your use case

    void doSomething(const T& o) {}
    
    auto s = std::make_shared(...);
    // ...
    doSomething(*s);
    

    The underlying pointer can't be released during the method call

提交回复
热议问题