Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the compiler warn "returning address of 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 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: " << &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);
}
like image 253
fxam Avatar asked May 06 '12 10:05

fxam


1 Answers

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).

like image 83
Mat Avatar answered Oct 24 '22 23:10

Mat