通过引用或通过值将共享指针作为参数传递给类 [英] Passing a shared pointer by reference or by value as parameter to a class
问题描述
如果要复制到成员变量中,共享指针应该通过引用还是通过值作为参数传递给类?
Should a shared pointer be passed by reference or by value as a parameter to a class if it is going to be copied to a member variable?
共享指针的复制将增加引用计数,我不想制作任何不必要的副本,因此引用计数会增加.将共享指针作为参考传递会解决这个问题吗?我认为确实如此,但还有其他问题吗?
The copying of the shared pointer will increment the refrence count and I don't want to make any unnecessary copies and thus ref count increments. Will passing the shared pointer as a refrence solve this? I assume it does but are there any other problems with this?
按值传递:
class Boo {
public:
Boo() { }
};
class Foo {
public:
Foo(std::shared_ptr<Boo> boo)
: m_Boo(boo) {}
private:
std::shared_ptr<Boo> m_Boo;
};
int main() {
std::shared_ptr<Boo> boo = std::make_shared<Boo>();
Foo foo(boo);
}
通过引用:
class Boo {
public:
Boo() { }
};
class Foo {
public:
Foo(std::shared_ptr<Boo>& boo)
: m_Boo(boo) {}
private:
std::shared_ptr<Boo> m_Boo;
};
int main() {
std::shared_ptr<Boo> boo = std::make_shared<Boo>();
Foo foo(boo);
}
推荐答案
传值然后移入成员:
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.
这篇关于通过引用或通过值将共享指针作为参数传递给类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!