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

前端 未结 17 1746
日久生厌
日久生厌 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

    Yes, taking a reference is fine there. You don't intend to give the method shared ownership; it only wants to work with it. You could take a reference for the first case too, since you copy it anyway. But for first case, it takes ownership. There is this trick to still copy it only once:

    void ClassA::take_copy_of_sp(boost::shared_ptr sp) {
        m_sp_member.swap(sp);
    }
    

    You should also copy when you return it (i.e not return a reference). Because your class doesn't know what the client is doing with it (it could store a pointer to it and then big bang happens). If it later turns out it's a bottleneck (first profile!), then you can still return a reference.


    Edit: Of course, as others point out, this only is true if you know your code and know that you don't reset the passed shared pointer in some way. If in doubt, just pass by value.

提交回复
热议问题