C++怎么使用T*或T&参数

本篇内容主要讲解“C++怎么使用T*或T&参数”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++怎么使用T*或T&参数”吧!

对于通常的使用场景,应该使用T*或T&参数而非智能指针。

Reason(原因)

传递一个智能指针来转交或分享所有权的方式应该只在希望表现所有权语义时使用(参见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.

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.

        内容从未被修改或者没有传递给可以修改其内容的函数。

到此,相信大家对“C++怎么使用T*或T&参数”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!