簡體   English   中英

將本地引用返回到本地變量時,編譯器為什么不警告“返回本地變量或臨時地址”?

[英]Why doesn't the compiler warn “returning address of local variable or temporary” when returning a local reference to a local variable?

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

是的,這仍然是錯誤的。

編譯器無法檢測到您在做危險(或非法)事情的所有情況。 它會在找到它們時發出警告,但無法識別所有情況(也不一定)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM