您的位置 首页 > 腾讯云社区

C++核心准则编译边学-F.44 在不希望得到拷贝而且不需要返回值为空时返回T&---面向对象思考

F.44: Return a T& when copy is undesirable and "returning no object" isn't needed

F.44 在不希望得到拷贝而且不需要返回值为空时返回T&。

译者注:不希望的到拷贝的含义是只是调用接口。

Reason(原因)

The language guarantees that a T& refers to an object, so that testing for nullptr isn't necessary.

语言保证T&一定会参照某个对象,因此不需要nullptr检查。

See also: The return of a reference must not imply transfer of ownership:discussion of dangling pointer prevention and discussion of ownership.

参见:返回引用时一定不要包含传递所有权的含义:关于防止悬空指针的讨论,关于所有权的讨论。

Example(示例)class Car { array<wheel, 4> w; // ... public: wheel& get_wheel(int i) { Expects(i < w.size()); return w[i]; } // ... }; void use() { Car c; wheel& w0 = c.get_wheel(0); // w0 has the same lifetime as c }Enforcement(实施建议)

Flag functions where no return expression could yield nullptr。

标示没有返回表达式生成nullptr的函数。

译者注:这个建议应该仅限于返回值是指针类型的函数。

觉得本文有帮助?请分享给更多人。

关注【面向对象思考】,轻松学习每一天!

有任何疑问,欢迎留言提问或讨论。

面向对象设计,面向对象编程,面向对象思考!

---来自腾讯云社区的---面向对象思考

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: