1 引用必须引一块合法的内存空间
int test4() {
int &a = 10;
}
2 不要返回局部变量的引用
int & doWork() {
int a = 10;
return a;
//C4172:returning address of local variable or temporary
}
int test4() {
//int &a = 10;
int &ret = doWork();
//cout << "ret=" << ret << endl;
//Error C4716 'test4': must return a value
}
错误C4172:returning address of local variable or temporary
返回了局部或临时变量
不是不能返回局部变量,是不能返回指向局部变量的指针和引用。
因为局部变量在函数退出时就被mark为无效了,所以函数结束后所返回的这个地址不能确保包含能被接下来的代码使用的正确的值。
int & doWork2() {
static int a = 10;
return a;
}
int test5() {
int &ret = doWork2();
cout << "ret=" << ret << endl; //10
cout << "ret=" << ret << endl; //10
}
3 如果函数的返回值是引用,那么这个函数调用可以作为左值
doWork2()=1000; //相当于写了a=1000