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

前端 未结 17 1652
日久生厌
日久生厌 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 01:47

    I would advocate passing shared pointer by const reference - a semantics that the function being passed with the pointer does NOT own the pointer, which is a clean idiom for developers.

    The only pitfall is in multiple thread programs the object being pointed by the shared pointer gets destroyed in another thread. So it is safe to say using const reference of shared pointer is safe in single threaded program.

    Passing shared pointer by non-const reference is sometimes dangerous - the reason is the swap and reset functions the function may invoke inside so as to destroy the object which is still considered valid after the function returns.

    It is not about premature optimization, I guess - it is about avoiding unnecessary waste of CPU cycles when you are clear what you want to do and the coding idiom has firmly been adopted by your fellow developers.

    Just my 2 cents :-)

提交回复
热议问题