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的函数。

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

 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值