来自 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 thereturn
statement.
也就是说,临时对象甚至在函数退出之前就被销毁了,因此您的程序会引发未定义的行为。
1 我可以继续引用整个列表来说明为什么会这样,但这可能会浪费答案空间。
关于c++ - 返回对临时(内置类型)的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559817/