当在Visual Studio 2010中编译以下代码时,会出现这种情况。我的问题是:C++编译器会警告如果一个函数返回局部变量的地址,但为什么在返回对局部变量的本地引用时不会发出警告?这样做仍然是错误的吗(返回局部变量的本地引用),只是编译器无法检测到吗?检查“num”和“r”的地址会发现它们共享相同的内存位置。
#include <iostream>
using namespace std;
int & intReference() {
int num = 5;
int &r = num;
cout << "\nAddress of num: " << #
//return num; // Compiler warning: C4172: returning address of local variable or temporary
return r; // No warning?
}
void main() {
int &k = intReference();
cout << "\nk = " << k; // 5
cout << "\nAddress of k: " << &k; // same address as num
char c;
cin.get(c);
}