我们应该通过引用还是通过值传递 shared_ptr ?

2021-12-24 00:00:00 c++ c++11 boost shared-ptr

当一个函数接受一个 shared_ptr(来自 boost 或 C++11 STL)时,你是否通过了它:

When a function takes a shared_ptr (from boost or C++11 STL), are you passing it:

  • 通过常量引用:void foo(const shared_ptr<T>& p)

或按值:void foo(shared_ptr p) ?

我更喜欢第一种方法,因为我怀疑它会更快.但这真的值得吗?还有其他问题吗?

I would prefer the first method because I suspect it would be faster. But is this really worth it or are there any additional issues?

能否请您说明您选择的理由,或者如果情况如此,您认为这无关紧要的原因是什么.

Could you please give the reasons for your choice or if the case, why you think it does not matter.

推荐答案

Scott、Andrei 和 Herb 在 问我们任何问题 会话在 C++ 及 2011 年以后.从 4:34 开始观看 关于shared_ptr 性能和正确性.

This question has been discussed and answered by Scott, Andrei and Herb during Ask Us Anything session at C++ and Beyond 2011. Watch from 4:34 on shared_ptr performance and correctness.

简而言之,没有理由传递值,除非目标是共享对象的所有权(例如,在不同的数据结构之间,或在不同的线程之间).

Shortly, there is no reason to pass by value, unless the goal is to share ownership of an object (eg. between different data structures, or between different threads).

除非您可以像 Scott Meyers 在上面链接的谈话视频中解释的那样对其进行移动优化,但这与您可以使用的 C++ 的实际版本有关.

Unless you can move-optimise it as explained by Scott Meyers in the talk video linked above, but that is related to actual version of C++ you can use.

在 GoingNative 2012 会议的 交互式面板:问我们任何问题!值得一看,尤其是来自 22:50.

A major update to this discussion has happened during GoingNative 2012 conference's Interactive Panel: Ask Us Anything! which is worth watching, especially from 22:50.

相关文章