我们应该按引用还是按值传递shared_ptr? [英] Should we pass a shared_ptr by reference or by value?

查看:103
本文介绍了我们应该按引用还是按值传递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:

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

或按值:void foo(shared_ptr<T> 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在shared_ptr性能和正确性的04m34s"rel =" noreferrer>.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆