智能指針(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&).