且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过引用或通过值将共享指针作为参数传递给类

更新时间:2023-11-08 23:06:52

传值然后移入成员:

class Foo {
public:
    Foo(std::shared_ptr<Boo> boo) 
        : m_Boo(std::move(boo)) {}
private:
    std::shared_ptr<Boo> m_Boo;
};

这在所有情况下都是最有效的——如果调用者有一个右值引用,那么就不会有一个 add-ref,如果调用者有一个值,就会有一个 add-ref.

This will be the most efficient in all cases - if the caller has a rvalue-reference then there wont be a single add-ref, if the caller has a value there'll be a single add-ref.

如果您通过了 const&,即使在不必要的情况下,您也会强制添加引用.如果您按值传递然后在没有 std::move 的情况下进行设置,您可能会得到 2 个 add-refs.

If you pass by const& you force an add-ref even in cases where its unnecessary. If you pass by value and then set without a std::move you may get 2 add-refs.

如果您有一个移动比复制便宜得多的类,并且您有一个始终复制传入的实例的函数调用,那么这是一个很好的模式 - 就像在这种情况下一样.您通过按值获取它来强制复制在函数调用边界发生,然后如果调用者有一个右值引用,则复制根本不需要发生 - 它会被移动.

This is a good pattern to use if you've got a class where a move is significantly cheaper than a copy, and you have a function call which will always copy the instance passed in - as in this case. You force the copy to happen at the function call boundary by taking it by value, and then if the caller has a rvalue reference the copy need never happen at all - it will be moved instead.