将临时对象绑定到常量引用
binding a temporary object to a const reference
#include <iostream>
using namespace std;
int f()
{
int x=1;
return x;
}
int main()
{
const int& s = f();
cout << s << endl;
}
#include <iostream>
using namespace std;
int x=1;
int &f()
{
return x;
}
int main()
{
const int& s = f();
cout << s << endl;
}
这两个程序都是正确的。但是当我使用
int &f()
{
int x=1;
return x;
}
而不是
int f()
{
int x=1;
return x;
}
我收到一个错误:
main.cpp:在函数'int& f(('中:
main.cpp:6:13: 警告:返回对局部变量 'x' 的引用 [-Wreturn-local-addr]
int x=1;
^
bash:第 7 行:14826 分段错误(核心转储(./a.out
怎么了?
int &f()
{
int x=1;
return x;
// x reside on the function calling stack and it is temporary
// when you return the reference to x, after the function has returned,
// x is not there anymore(local variable)
}
如果确实要返回对函数内声明的变量的引用,请考虑将其分配给堆,或将其声明为静态变量
int &f()
{
int* x= new int;
*x = 1;
return *x;
}
int main(){
int& a = f();
cout << a; // 1
delete &a;
// and MAKE SURE you delete it when you don't need it
}
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- 通过常量引用传递参数的矩阵模板类
- 在C++中使用非常量引用作为常量
- 具有常量引用参数的函数模板专用化
- 多个"常量引用"变量可以共享同一个内存吗?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 为什么常量方法可以采用非常量引用?
- 为什么当我们有常量引用时创建临时对象?
- 如何返回向量的常量引用?
- C++:常量引用参数
- 不同于按值传递和常量引用传递的程序集
- 为什么const_cast和static_cast常量引用没有效果?
- C++ 获取函数在常量引用中按值返回的结果
- 从 BubbleSort* 类型的右值初始化 'AssortedSorter&' 类型的非常量引用无效"
- C++ 在类中使用常量引用文本时 O2 内存泄漏
- 是否可以跨 dll 边界返回常量引用/指向 std::vectors?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?
- 通过非常量引用参数修改常量引用参数
- 将常量引用传递给线程
- 为什么C++中没有常量引用,就像常量指针一样?