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的函数。
译者注:这个建议应该仅限于返回值是指针类型的函数。
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】