c++ - 返回对临时(内置类型)的引用

标签 c++ reference return temporary

来自 this thread很明显,字符串文字不能用于返回 const string& 的函数,因为存在从 const char* 到 std::string 的隐式转换,这会创建一个临时对象。

但是如果我的返回类型完全匹配并且不需要转换,为什么我会收到警告“警告:返回对临时对象的引用”,例如:

include <iostream>

const int& test(){
    return 2;
}

int main(){

    std::cout << test();

}

返回值 2 不需要隐式转换,所以为什么会出现警告?我认为使用 test() 和做几乎一样

 const int& example = 2;

这是完全有效的。此外,如果我将 2 更改为 2.2(因此它是一个 double )程序仍然运行(具有相同的警告)尽管事实上存在从 double 到整数的转换?如果存在从 double 到 int 的转换,我是否应该遇到类似于 const char* 返回到字符串引用的问题?

最佳答案

仍然创建临时文件。 §8.5.3/(5.2.2.2) 适用1:

Otherwise, a temporary of type “ cv1 T1” is created and copy-initialized (8.5) from the initializer expression. The reference is then bound to the temporary.

这也适用于您的第二个示例。它不适用于类类型的 prvalues 或标量 xvalues:两者

const A& a = A();
// and
const int& i = std::move(myint);

暂不介绍。然而,这并没有改变最终结果:在任何情况下,绑定(bind)到引用的临时对象将在 return 语句结束时被销毁 - §12.2/(5.2):

The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

也就是说,临时对象甚至在函数退出之前就被销毁了,因此您的程序会引发未定义的行为。


1 我可以继续引用整个列表来说明为什么会这样,但这可能会浪费答案空间。

关于c++ - 返回对临时(内置类型)的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559817/

相关文章:

C++ const 访问器和引用最佳实践

ruby - 如何获得对方法的引用?

c - 在函数中有两个return 语句,将执行哪个return 语句?

php - 用于向 HTML 文档中的 .js 和 .css 引用添加版本号的正则表达式

c++ - 迭代 QML XYSeries 中的点

c++ - GameBoy 经典模拟器 - 如何初始化 VRAM (0x8000)

使用 cmake 将 OpenCV 作为外部的 C++ 项目

python - 将列表的元素作为 Python 中的单个项目返回

java - 由于返回太早,方法返回错误值

c++ - 如何将任意结构数组传递给函数?