【发布时间】:2016-12-09 16:30:51
【问题描述】:
这是什么意思
fun()=30;
count<<fun();
函数定义为:
int &fun()
{
static int x = 10;
return x;
}
【问题讨论】:
-
这与this问题有关
-
这是一个经典的反模式,因为函数的正常意义是它返回的结果是其参数有时与非可变状态信息混合的结果。大多数 C++ 程序员都认为它是一个返回非常量引用的函数。返回 ref 的函数应该返回 const ref 是一种很好的做法。
-
请注意,返回非
const引用并不始终是一种反模式。有效的用例是providing a non-constversion of an operator such asoperator[](例如std::vector所做的),或者在Builder 模式中(Builderclass' setters returnBuilder&, so that they can be chained together)。
标签: c++