Life Scope of Temporary Variable
Asked Answered
A

1

6
#include <cstdio>
#include <string>

void fun(const char* c)
{
    printf("--> %s\n", c);
}

std::string get()
{
    std::string str = "Hello World";
    return str;
}

int main() 
{
    const char *cc = get().c_str();
    // cc is not valid at this point. As it is pointing to
    // temporary string internal buffer, and the temporary string
    // has already been destroyed at this point.
    fun(cc);

    // But I am surprise this call will yield valid result.
    // It seems that the returned temporary string is valid within
    // scope (...)
    // What my understanding is, scope means {...}
    // Is this valid behavior guarantee by C++ standard? Or it depends
    // on your compiler vendor implementations?
    fun(get().c_str());

    getchar();
}

The output is :

-->
--> Hello World

Hello, may I know the correct behavior is guarantee by C++ standard, or it depends on your compiler vendor implementations? I have tested this under VC2008 and VC6. Works fine for both.

Aptitude answered 15/6, 2010 at 1:3 Comment(2)
Duplicate of: #2507293Cloudlet
By the way, your get function can be simplified to: std::string get() { return "Hello World"; }Luxurious
C
10

See this question. The standard guarantees that a temporary lives until the end of the expression of which it is a part. Since the entire function invocation is the expression, the temporary is guaranteed to persist until after the end of the function invocation expression in which it is a part.

Cloudlet answered 15/6, 2010 at 1:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.