Home > Backend Development > C++ > ## Why Does Calling `std::string.c_str()` on a Returned String Lead to Undefined Behavior?

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

Linda Hamilton
Release: 2024-10-25 11:29:02
Original
656 people have browsed it

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

Why Does Calling std::string.c_str() on a Returned String Fail?

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

As you might expect, getString() returns a copy of its local string, seemingly keeping it alive in main(). However, the code unexpectedly prints garbage. This raises the question: when and why is the returned string destroyed?

The answer lies in the nature of temporaries in C . getString() returns a temporary std::string that is created within the function and is destroyed upon completion of the statement in which it is returned. This means that by the time cStr points to the string's underlying character array, the temporary has already been destroyed, and cStr becomes a dangling pointer, leading to undefined behavior.

To resolve this issue, the returned temporary can be bound to a named variable or reference, thereby extending its lifetime until the reference's scope ends:

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

Alternatively, the pointer to the underlying character array can be used before the temporary is destroyed:

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

The above is the detailed content of ## Why Does Calling `std::string.c_str()` on a Returned String Lead to Undefined Behavior?. 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