F.7: For general use, take T*
or T&
arguments rather than smart pointers
对于通常的使用场景,应该使用T*或T&参数而非智能指针。
Reason(原因)
Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended (see R.30). Passing by smart pointer restricts the use of a function to callers that use smart pointers. Passing a shared smart pointer (e.g., std::shared_ptr
) implies a run-time cost.
传递一个智能指针来转交或分享所有权的方式应该只在希望表现所有权语义时使用(参见R.30)。通过智能指针传递参数限定了只有使用智能指针的调用者才能使用该函数。传递共享智能指针(例如,std::shared_ptr)必然包含运行时代价。
译者注:代价包括但并不限于管理引用计数
Example(示例)
// accepts any int*void f(int*);
// can only accept ints for which you want to transfer ownershipvoid g(unique_ptr<int>);
// can only accept ints for which you are willing to share ownershipvoid g(shared_ptr<int>);
// doesn't change ownership, but requires a particular ownership of the callervoid h(const unique_ptr<int>&);
// accepts any intvoid h(int&);
Example, bad(反面示例)
// calleevoid f(shared_ptr<widget>& w){ // ... use(*w); // only use of w -- the lifetime is not used at all // ...};
See further in R.30.(进一步的信息请参考R.30)
Note(注意)
We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers.
我们可以静态捕捉悬空指针,因此不需要依靠资源管理来避免发生悬空指针违反。
译者注:悬空指针是指指向已经释放的内存的指针;野指针是没有初始化的指针。
See also:(参考)
- Prefer
T*
over T&
when "no argument" is a valid option
当没有参数是有效选项时应该使用T*而不是T& - Smart pointer rule summary
智能指针使用概括
译者注:反过来,当不希望参数为空是可以使用T&。
Enforcement(实施建议)
Flag a parameter of a smart pointer type (a type that overloads operator->
or operator*
) for which the ownership semantics are not used; that is
标记不包含所有权语义的智能指针类型参数(重载了->和*运算符的类型);即
- copyable but never copied/moved from or movable but never moved
可复制但是从来没有被复制或移动或者可移动却从来没有移动 - and that is never modified or passed along to another function that could do so.
内容从未被修改或者没有传递给可以修改其内容的函数。
阅读更多更新文章,请关注微信公众号【面向对象思考】