簡體   English   中英

返回引用返回函數的局部引用與局部變量

[英]Returning the local reference versus local variable of the reference-returning-function

我知道對於返回引用的函數,返回局部變量的引用是一種未定義的行為。 例如,

int& test(int a) {
    return a;
}

編譯器會發出

<source>: In function 'int& test(int)':

<source>:4:9: warning: reference to local variable 'a' returned [-Wreturn-local-addr]

    4 |  return a;

      |         ^

<source>:3:15: note: declared here

    3 | int& test(int a) {

      |           ~~~~^

但令人驚訝的是,如果我在函數內部定義引用並返回它,編譯器就不會再抱怨了。

int& test(int a) {
    int& b = a;
    return b;
}

為什么這是有效的情況? 無論如何b不引用局部變量嗎?

僅僅因為你偽造了檢查器並不意味着這段代碼突然表現良好,事實並非如此。

返回對臨時局部變量的引用是未定義的行為。 編譯器會捕獲瑣碎的情況,但不會捕獲所有情況。

未定義行為的問題在於,您可以在沒有意識到的情況下擁有它。 沒有警告。 沒有錯誤。 除了您的程序表現不佳外,根本沒有任何跡象。

但令人驚訝的是,如果我在函數內部定義引用並返回它,編譯器就不會再抱怨了。

我想這里的大問題是:什么編譯器?

用 g++ (9.2) 做一個快速測試,我得到:

trash9.cpp: In function 'int& test(int)':
trash9.cpp:3:12: warning: function returns address of local variable [-Wreturn-local-addr]
    3 |     return b;
      |            ^
trash9.cpp:1:15: note: declared here
    1 | int& test(int a) {
      |           ~~~~^

使用 VC++ (19.28),事情稍微復雜一點。 如果我單獨編譯該函數,則不會收到警告,但如果我將其與調用它的一些代碼一起編譯,則會收到警告:

C:\C\source\trash9.cpp(3) : warning C4172: returning address of local variable or temporary: a

使用 clang++ (10.0),我得到:

trash9.cpp:3:12: warning: reference to stack memory associated with parameter 'a' returned [-Wreturn-stack-address]
    return b;
           ^
trash9.cpp:2:10: note: binding reference variable 'b' here
    int& b = a;
         ^   ~

所以我想如果我必須直接回答這個問題:不,它是無效的,是的,編譯器可以並且確實會警告它。

有些人可能聽我這么說感到厭煩,但我還是要再說一遍:至少有幾個編譯器是值得的——有時一個人會警告另一個人沒有的東西,警告可以告訴你關於一個可能更難自行查找和修復的問題。

暫無
暫無

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

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