c++copytemporary-objectsreturn-by-reference

How long does variable exist in temporary storage?


Currently I am learning C++ with 6th edition C++ Primer Plus by Steven Prata and on p. 389 I found smth very interesting that I would like to clarify for myself. If we have some function like this:

const std::string     &ft_add_on_sides(std::string s1, std::string s2)
{
        std::string          res;
        res = s2 + s1 + s2;
        return (s2);
}

int     main(void)
{
        std::string input = "Hello"
        std::string result = ft_add_on_sides(input, "###");
        return (0);
}

As far as I understand, this function is expecting two string objects which will be copies of those, which programmer will actually pass. And this function will return const reference to some memory address.
But I am interested in return statement:
As s1 or s2 are located in a temporary storage, we can gain access to them, but when will they be destroyed? Won't I get into troubles with such return statement?
Add. Cause the variable can be destroyed and I am still asking for its address.


Solution

  • Parameters of a function are destroyed as soon as the return statement has executed, before the calling function continues. That means you can still use these parameters inside the return value expression, but you'd better return a copy of them.

    What you wrote in your example is Undefined Behavior. Anything can happen. Typically, in debug modes compilers are reasonably good in catching accesses to destroyed strings, but in release builds the compiler no longer introduces code to catch bugs.