Search code examples
c++temporary-objects

Why can I still access a reference to a temporary object?


const std::string& f(){
    std::string s = "Hello";
    return s + s;
}
int main() {
    std::string s = "Hello";
    std::string& s1 = s + s;
    s1 += "!";
    std::cout << f();
}

I have a few questions about this code that I wrote.

Why can I still access and modify s1 even if it is a non-const reference to a temporary object?

Why does f give me a runtime error? I thought const would extend the lifetime of a temporary object?


Solution

  • Are you using Visual Studio by any chance? It allows your code using s1 to work as a language extension. I believe that part of the code is safe (ignoring whether it is good practice).

    Only a const reference local variable can extend the lifetime of a temporary. But it's never permitted to return a local variable by reference (unless it is static). Therefore your function f is invalid.