Why does the compiler not warn "return the address of a local variable or temporary" when returning a local reference to a local variable?

This happens when compiling the following code in Visual Studio 2010. My question is: the C ++ compiler will warn if the function returns the address of a local variable, but why doesn't it warn when returning a local link to a local variable?

Is it still wrong (returning a local reference to a local variable), but just that the compiler could not detect it? Examining the addresses "num" and "r" shows that they have the same memory location.

#include <iostream>  
using namespace std;

int & intReference() {
  int num = 5;
  int &r = num;
  cout << "\nAddress of num: " << &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);
}
+5
source share
1 answer

Yes, this is still wrong.

, ( ) . , , ( ).

+6

All Articles