为什么在将本地引用返回到局部变量时,编译器不会警告“返回局部变量或临时地址”?

时间:2012-05-06 10:20:30

标签: c++ visual-studio-2010

在Visual Studio 2010中编译以下代码时会发生这种情况。我的问题是:如果函数返回局部变量的地址,C ++编译器将发出警告,但为什么在将本地引用返回到本地时不会发出警告变量?

它仍然是错误的(返回本地变量的本地引用),但只是编译器无法检测到它?检查'num'和'r'的地址表明它们共享相同的内存位置。

#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);
}

1 个答案:

答案 0 :(得分:6)

是的,它仍然是错的。

编译器无法检测到您正在执行危险(或非法)操作的所有情况。它会在找到它们时发出警告,但它无法识别所有情况(并且不必识别)。

相关问题