我正在阅读 the Wikipedia page about references .
它包含以下代码:
int& preinc(int& x)
{
return ++x; // "return x++;" would have been wrong
}
preinc(y) = 5; // same as ++y, y = 5
我确实尝试使用 return x++;
而不是 return++x;
进行编译。正如预测的那样,这导致了以下错误:
error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
我不明白这个错误。我有一种模糊的直觉,即 x 的增量发生得太晚了(即,在 preinc 的函数调用结束之后)。但是,我不认为这是一个问题,因为变量 x 从未停止存在。欢迎任何解释。
最佳答案
错误的原因是post increment x++
返回一个临时值,而这不能绑定(bind)到非常量左值引用。这是同一问题的简化版本:
int i = 42;
int& j = i++; // Error: i++ returns temporary value, then increments i.
const int& k = i++; // OK, const reference can bind to temporary.
关于c++ - 引用类型返回函数和后缀增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18034513/