C++ - passing references to std::shared_ptr or boost::shared_ptr

前端 未结 17 1687
日久生厌
日久生厌 2020-11-28 01:20

If I have a function that needs to work with a shared_ptr, wouldn\'t it be more efficient to pass it a reference to it (so to avoid copying the shared_ptr

17条回答
  •  借酒劲吻你
    2020-11-28 02:08

    I would avoid a "plain" reference unless the function explicitely may modify the pointer.

    A const & may be a sensible micro-optimization when calling small functions - e.g. to enable further optimizations, like inlining away some conditions. Also, the increment/decrement - since it's thread safe - is a synchronization point. I would not expect this to make a big difference in most scenarios, though.

    Generally, you should use the simpler style unless you have reason not to. Then, either use the const & consistently, or add a comment as to why if you use it just in a few places.

提交回复
热议问题