Should we pass a shared_ptr by reference or by value?(我们应该通过引用还是通过值传递 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
?
我更喜欢第一种方法,因为我怀疑它会更快.但这真的值得吗?还有其他问题吗?
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.
这篇关于我们应该通过引用还是通过值传递 shared_ptr ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我们应该通过引用还是通过值传递 shared_ptr ?


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01