Home > Backend Development > C++ > body text

Here are a few title options that fit the question-answer format and accurately describe the article\'s content: **Option 1 (Short & Direct):** * **Why Does Calling `std::string.c_str()` on a Re

Patricia Arquette
Release: 2024-10-25 09:23:02
Original
674 people have browsed it

Here are a few title options that fit the question-answer format and accurately describe the article's content:

**Option 1 (Short & Direct):**

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

**Option 2 (M

Why Calling std::string.c_str() on a Function Returning a String Fails

Consider the following code:

<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>
Copy after login

Intuitively, one would expect the returned temporary string from getString() to remain valid in main()'s scope. However, this is incorrect.

The issue lies in the lifetime of temporary objects in C . A temporary object is destroyed at the end of the expression in which it's created, unless it's bound to a reference or used to initialize a named object. In this case, getString() returns a temporary string, which is destroyed at the end of the expression in main().

Consequently, cStr holds a dangling pointer, and using it can lead to undefined behavior. To avoid this problem, one can use a named variable or reference to ensure the validity of the returned string. For instance:

<code class="cpp">std::string returnedString = getString();
const char* cStr = returnedString.c_str();
std::cout << cStr << std::endl; // Safe</code>
Copy after login

Alternatively, the temporary string can be used directly without assigning it to a variable:

<code class="cpp">std::cout << getString().c_str() << std::endl; // Also safe</code>
Copy after login

The above is the detailed content of Here are a few title options that fit the question-answer format and accurately describe the article\'s content: **Option 1 (Short & Direct):** * **Why Does Calling `std::string.c_str()` on a Re. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!