为什么编译器在返回对局部变量的局部引用时不警告"returning address of local variable or temporary"?

Why doesn't the compiler warn "returning address of local variable or temporary" when returning a local reference to a local variable?

本文关键字:of address returning local variable temporary or 警告 返回 编译器 局部变量      更新时间:2023-10-16

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

是的,它仍然是错误的。

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