当一个函数接受一个shared_ptr(来自boost或c++ 11 STL)时,你是否传递它:
foo(const shared_ptr<T>& p) 或通过值:void foo(shared_ptr<T> p) ?
我更喜欢第一种方法,因为我怀疑它会更快。但这真的值得吗,还有其他问题吗?
你能否给出你选择的原因,或者如果是这样,为什么你认为这无关紧要。
当一个函数接受一个shared_ptr(来自boost或c++ 11 STL)时,你是否传递它:
foo(const shared_ptr<T>& p) 或通过值:void foo(shared_ptr<T> p) ?
我更喜欢第一种方法,因为我怀疑它会更快。但这真的值得吗,还有其他问题吗?
你能否给出你选择的原因,或者如果是这样,为什么你认为这无关紧要。
当前回答
Shared_ptr不够大,它的构造函数\析构函数也没有做足够的工作,因此拷贝有足够的开销来关心按引用传递和按复制传递的性能。
其他回答
通过const引用传递,它更快。如果你需要存储它,比如在某个容器中,引用计数将通过复制操作自动神奇地增加。
就我个人而言,我会使用const引用。没有必要为了函数调用而增加引用计数。
Shared_ptr不够大,它的构造函数\析构函数也没有做足够的工作,因此拷贝有足够的开销来关心按引用传递和按复制传递的性能。
由于不知道shared_copy复制操作的时间成本,我遇到了更高的CPU使用问题。我从来没有想到原子增量和减量会付出这么大的代价。
根据我的测试结果,int32原子增量和减量比非原子增量和减量需要2倍或40倍的时间。我用的是3GHz Core i7, Windows 8.1。前者在不发生争用时得出,后者在发生争用可能性较大时得出。我始终牢记原子操作是基于硬件的锁。锁就是锁。发生争用时对性能不利。
遇到这种情况,我总是使用byref(const shared_ptr&)而不是byval(shared_ptr)。
以下是Herb Sutter的观点
Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership. Guideline: Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter. Guideline: Use a non-const shared_ptr& parameter only to modify the shared_ptr. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).