c++ - 引用类型返回函数和后缀增量

标签 c++ reference post-increment

我正在阅读 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/

相关文章:

c++ - 如何检查模板参数是否为结构/类?

multithreading - IOCP多线程服务器和引用计数类

rust - 结构的可变性

c++ - 为什么我不需要检查引用是否无效/空?

java - for 循环中的前后增量

java - Math.min() 中后递增运算符的有趣行为

c++ - 与 -static 链接时出现 Valgrind 错误——为什么?

c++ - 在 Linux 上使用 C++ 库

c++ - 由于 openCV C++ 中的调试错误,视频文件在两者之间停止

c - C中的后增量和前增量