临时变量的寿命范围

时间:2010-06-15 01:03:03

标签: c++

#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();
}

输出结果为:

-->
--> Hello World

您好,我是否可以通过C ++标准了解正确的行为,还是取决于您的编译器供应商实现?我在VC2008和VC6下进行了测试。适用于两者。

1 个答案:

答案 0 :(得分:10)

this question。该标准保证临时生命直到它所属的表达结束。由于整个函数调用是表达式,因此临时性保证一直持续到函数调用表达式结束后才成为它的一部分。