簡體   English   中英

警告 C4172:返回對綁定到局部變量的 const std::string 的引用。 它有多安全?

[英]Warning C4172: Returning a reference to const std::string bound to a local variable. How safe is it?

我剛剛在工作中構建我們的一個項目,我看到添加了一個新的 function:

const std::string& ClassName::MethodName() const
{
   return "";
}

編譯器給出警告:

警告 C4172:返回局部變量或臨時地址

我認為編譯器是對的。 這個 function 有多安全?

請注意, function 不會返回const char* ,因為字符串文字具有 static 存儲持續時間。 它返回對const std::string的引用

是的,它不安全。
返回局部變量或臨時變量的地址並取消引用它會導致未定義的行為。

正如你評論的:
是的,臨時綁定到常量引用的生命周期會增加,直到常量的生命周期。 但這需要調用者接受 const 引用中的返回值,因此 function 本身並不安全。

來自 C++ 標准:
C++03 12.2 臨時對象

第二個上下文是引用綁定到臨時的。 引用綁定到的臨時對象或作為臨時對象綁定的子對象的完整 object 的臨時對象在引用的生命周期內持續存在,除非以下指定...

臨時綁定到構造函數的 ctor-initializer (12.6.2) 中的引用成員將持續存在,直到構造函數退出。 A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits

在編譯器內部執行您實際執行的操作:

const std::string* ClassName::MethodName() const
{
   std::string temp = "";
   return &temp;
}

並且返回對局部變量的引用或指針是不好的。

在某些情況下,此代碼是安全的。 參見GotW #88: A Candidate For the “最重要的 const”

這是一個讓我明白的例子:

#include <iostream>
using std::cout;
struct A{
   A()   {
      cout << "Ctor\n";
   }
   ~A()   {
      cout << "Dtor\n";
   }
};

const A& f(){
   return A();
}

int main(){
   const A& ref = f();
   cout << "1\n";
   {
      const A& ref1 = A();
      cout << "2\n";
   }
   cout << "3\n";
}

輸出

Ctor
Dtor
1
Ctor
2
Dtor
3

暫無
暫無

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

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