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

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

    It seems that all the pros and cons here can actually be generalised to ANY type passed by reference not just shared_ptr. In my opinion, you should know the semantic of passing by reference, const reference and value and use it correctly. But there is absolutely nothing inherently wrong with passing shared_ptr by reference, unless you think that all references are bad...

    To go back to the example:

    Class::only_work_with_sp( foo &sp ) //Again, no copy here  
    {    
        ...  
        sp.do_something();  
        ...  
    }
    

    How do you know that sp.do_something() will not blow up due to a dangling pointer?

    The truth is that, shared_ptr or not, const or not, this could happen if you have a design flaw, like directly or indirectly sharing the ownership of sp between threads, missusing an object that do delete this, you have a circular ownership or other ownership errors.

提交回复
热议问题