首頁  >  文章  >  後端開發  >  以下是一些適合您文章內容的基於問題的標題: **直接且專注:** * **為什麼在臨時字串上呼叫 `std::string.c_str()` 會導致未定義的行為? * **

以下是一些適合您文章內容的基於問題的標題: **直接且專注:** * **為什麼在臨時字串上呼叫 `std::string.c_str()` 會導致未定義的行為? * **

DDD
DDD原創
2024-10-26 10:25:03439瀏覽

Here are a few question-based titles that fit the content of your article:

**Direct and Focused:**

* **Why Does Calling `std::string.c_str()` on a Temporary String Lead to Undefined Behavior?**
* **How to Safely Use `std::string.c_str()` with Temporary

在臨時字串上呼叫std::string.c_str()

在C 中,臨時物件在字串末尾被銷毀它被創建時的完整表達。在給定的程式碼中,行 const char* cStr = getString().c_str();根據 getString() 的回傳值建立一個臨時 std::string 物件。但是,這個臨時變數在 cStr 指標可以使用它之前就被銷毀了。

要解決此問題,您可以將臨時變數儲存在命名變數中,或將其綁定到 const 左值引用或右值引用。例如:

<code class="cpp">std::string s = getString();      // Extended lifetime
const char* cStr1 = s.c_str();
std::cout << cStr1 << std::endl; // Safe

const std::string& s2 = getString();  // Const lvalue-reference
const char* cStr2 = s2.c_str();
std::cout << cStr2 << std::endl; // Safe</code>

或者,您可以在臨時物件被銷毀之前使用指標:

<code class="cpp">std::cout << getString().c_str() << std::endl;  // Temporary used immediately</code>

以上是以下是一些適合您文章內容的基於問題的標題: **直接且專注:** * **為什麼在臨時字串上呼叫 `std::string.c_str()` 會導致未定義的行為? * **的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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