引用返回值时出错
error on reference to return value
此代码无法通过编译。唯一的区别是返回类型。Foo1 的返回类型是用户定义的结构体,Foo2 的返回类型是 int。
struct test
{
};
test Foo1()
{
return test();
}
int Foo2()
{
return 0;
}
int main()
{
test& r1 = Foo1(); //ok
int& r2 = Foo2(); //no but why? Is it the C++ standard way?
return 0;
}
它要么是编译器错误,要么是它的"语言扩展"(例如MS VC++有许多这样的"语言扩展")。在函数调用的两种情况下,编译器都会发出错误,因为它可能不会将临时对象绑定到非 const 引用。
如果你想有一个引用,你仍然可以使用对 const 的引用,否则两行都不会编译:
struct test
{
};
test Foo1()
{
return test();
}
int Foo2()
{
return 0;
}
int main()
{
const test& r1 = Foo1(); // ok now
const int& r2 = Foo2(); //ok now
return 0;
}
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 方法错误"not all control paths return a value"和方法不返回值
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 对fread的返回值感到困惑
- 引用返回值时出错
- C++从构造函数返回值时出错
- 尝试存储映射插入的返回值时出错
- 当函数没有显式返回值时,如何强制编译器出错
- 创建输出文件 .rdstate() 时出错,返回值 2