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

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

    One thing that I haven't seen mentioned yet is that when you pass shared pointers by reference, you lose the implicit conversion that you get if you want to pass a derived class shared pointer through a reference to a base class shared pointer.

    For example, this code will produce an error, but it will work if you change test() so that the shared pointer is not passed by reference.

    #include 
    
    class Base { };
    class Derived: public Base { };
    
    // ONLY instances of Base can be passed by reference.  If you have a shared_ptr
    // to a derived type, you have to cast it manually.  If you remove the reference
    // and pass the shared_ptr by value, then the cast is implicit so you don't have
    // to worry about it.
    void test(boost::shared_ptr& b)
    {
        return;
    }
    
    int main(void)
    {
        boost::shared_ptr d(new Derived);
        test(d);
    
        // If you want the above call to work with references, you will have to manually cast
        // pointers like this, EVERY time you call the function.  Since you are creating a new
        // shared pointer, you lose the benefit of passing by reference.
        boost::shared_ptr b = boost::dynamic_pointer_cast(d);
        test(b);
    
        return 0;
    }
    

提交回复
热议问题