首頁  >  文章  >  後端開發  >  ## 為什麼在傳回的字串上呼叫 `std::string.c_str()` 會導致未定義的行為?

## 為什麼在傳回的字串上呼叫 `std::string.c_str()` 會導致未定義的行為?

Linda Hamilton
Linda Hamilton原創
2024-10-25 11:29:02591瀏覽

## Why Does Calling `std::string.c_str()` on a Returned String Lead to Undefined Behavior?

為什麼在傳回的字串上呼叫 std::string.c_str() 會失敗?

考慮以下程式碼:

<code class="cpp">std::string getString() {
    std::string str("hello");
    return str;
}

int main() {
    const char* cStr = getString().c_str();
    std::cout << cStr << std::endl; // Outputs garbage
}</code>

如您所料,getString() 傳回其本地字串的副本,似乎使其在 main() 中保持活動狀態。然而,程式碼意外地列印出垃圾訊息。這就提出了一個問題:返回的字串何時以及為何被銷毀?

答案在於 C 中臨時變數的本質。 getString() 傳回一個臨時 std::string,該臨時 std::string 在函數內創建,並在傳回它的語句完成後銷毀。這意味著當 cStr 指向字串的底層字元數組時,臨時變數已經被銷毀,並且 cStr 成為懸空指針,導致未定義的行為。

要解決此問題,可以將傳回的臨時變數綁定到命名變數或引用,從而延長其生命週期,直到引用的範圍結束:

<code class="cpp">std::string s1 = getString(); // s1 is initialized with a copy of the temporary
auto& s2 = getString(); // s2 binds to the temporary by reference</code>

或者,可以在銷毀臨時變數之前使用指向基礎字元陣列的指標:

<code class="cpp">std::cout << getString().c_str() << std::endl; // Temporary is destroyed after the expression completes</code>

以上是## 為什麼在傳回的字串上呼叫 `std::string.c_str()` 會導致未定義的行為?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn