重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

C++在什么时候使用智能指针作参数

本篇内容介绍了“C++在什么时候使用智能指针作参数”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

创新互联公司2013年开创至今,是专业互联网技术服务公司,拥有项目成都网站制作、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元胶州做网站,已为上家服务,为胶州各地企业和个人服务,联系电话:18980820575

R.30: 只有在包含明确的生命周期语义时使用智能指针作参数

Reason(原因)

如果一个函数只是需要一个部件本身,接受一个智能指针作参数是错误的。它应该可以接受所有部件对象,而不只是一个生命周期被按照特定方法管理的对象。不需要管理生命周期的函数应该使用原始的指针和引用。

Example, bad(反面示例)

// callee
void f(shared_ptr& w)
{
   // ...
   use(*w); // only use of w -- the lifetime is not used at all
   // ...
};

// caller
shared_ptr my_widget = /* ... */;
f(my_widget);

widget stack_widget;
f(stack_widget); // error
Example, good(范例)
// callee
void f(widget& w)
{
   // ...
   use(w);
   // ...
};

// caller
shared_ptr my_widget = /* ... */;
f(*my_widget);

widget stack_widget;
f(stack_widget); // ok -- now this works
Enforcement(实施建议)
  • (Simple) Warn if a function takes a parameter of a smart pointer type (that overloads operator-> or operator*) that is copyable but the function only calls any of: operator*, operator-> or get(). Suggest using a T* or T& instead.

  • (简单)如果一个函数使用了可拷贝的(重载了操作符->和操作符*的)智能指针类型的参数但是只是调用了运算符*、->或者get(),发出警告并建议使用T*或者T&。

  • Flag a parameter of a smart pointer type (a type that overloads operator-> or operator*) that is copyable/movable but never copied/moved from in the function body, and that is never modified, and that is not passed along to another function that could do so. That means the ownership semantics are not used. Suggest using a T* or T& instead.

  • 标记定义了(重载了操作符->和操作符*的)可拷贝/可移动智能指针类型的参数,但在函数体中却从未使用拷贝和移动功能,指针从未被修改也没有交给一个会那么做的函数的情况。那意味着所有权语义根本没有被使用。建议使用T*或者T&。

“C++在什么时候使用智能指针作参数”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


网页名称:C++在什么时候使用智能指针作参数
路径分享:http://cqcxhl.com/article/jpghog.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP