This happens when compiling the following code in Visual Studio 2010. My question is: the C++ compiler will warn if a function return the address of a local variable, but why doesn't it warn when returning a local reference to a local variable?
Is it still wrong (returning a local reference to a local variable), but just that the compiler couldn't detect it? Examining the addresses of 'num' and 'r' reveal that they share the same memory location.
#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);
}
Yes it's still wrong.
The compiler cannot detect all cases where you're doing dangerous (or illegal) things. It warns when it does find them, but it can't identify all cases (and doesn't have to).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.