智能指针(shared_ptr,unique_ptr)作为函数参数或者返回值时的一些注意事项

智能指针(shared_ptr,unique_ptr)作为函数参数或者返回值时的一些注意事项

当智能指针作为函数的参数或者返回值时,一直在纠结到底是用智能指针对象本身还是用原始指针。Herb Sutter大师的文章很好的解决了这个疑惑,参见网址:

https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/

       总结起来如下

1、 不要传递shared_ptr本身,而是用原始指针。因为会有性能损失,原子操作的自增自减等。

使用f(widget *w)

不使用f(shared_ptr< widget > w)

函数的返回值也是同样的道理。

2当表示所有权的转移时,用unique_ptr作为函数参数。

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: Prefer passing objects by value, *, or &, not by smart pointer.

Guideline: Express a “sink” function using a by-value unique_ptr parameter.

Guideline: Use a non-const unique_ptr& parameter only to modify the unique_ptr.

Guideline: Don’t use a const unique_ptr& as a parameter; use widget* instead.

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&).

原文地址:https://www.cnblogs.com/ljy339/p/11435265.html