Function Variable Persistence?

I'm not a newbie, but I'm hazy about how this works.

1
2
3
4
5
6
7
8
9
10
11

std::string return_msg_cpp()
{
    std::string str("hello");
    return str;
}

Called with:

std::string s2 = return_msg_cpp();


The string s2 now contains "hello".

How does the value of str survive the closing of the function?

What are the rules regarding a function's local variables and return value's persistence after the function's return?

The issue is this isn't returning some value, it's returning a reference to an instance of a string class who's scope has terminated.

Thanks.
Last edited on
Thanks TheIdeasMan:

Hugh?

I'm an idiot.

Can anybody explain this to an idiot? Please type slowly and use little words.

Would the code have worked prior to C++ 11?

Thanks.
Last edited on
> The issue is this isn't returning some value,
> it's returning a reference to an instance of a string class who's scope has terminated.

It is returning a prvalue (which has a result object of type std::string)

Without copy elision, the return statement would have involved making a copy of the local string str (move construction of the temporary); this copy/move operation is sequenced before the destruction of str.
Thanks JLBorges and TheIdeasMan:

This page does a pretty good job:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3055.pdf
n3055 is pre-C++17. C++17 further refined the notion of prvalue expressions.
In order to enable guaranteed copy elision, C++17 makes a distinction between prvalue expressions and the temporary result objects initialized by them.

In particular:
... temporary materialization does not occur when initializing an object from a prvalue of the same type (by direct-initialization or copy-initialization): such object is initialized directly from the initializer. This ensures "guaranteed copy elision".
https://en.cppreference.com/w/cpp/language/implicit_conversion#Temporary_materialization
Topic archived. No new replies allowed.