临时变量的生命周期

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

输出结果为:
-->
--> Hello World

你好,我想知道C++标准是否保证了正确的行为,还是取决于编译器供应商的实现?我已经在VC2008和VC6下进行了测试,两者都可以正常工作。


1
临时参数的生命周期:https://dev59.com/THE95IYBdhLWcg3wAo9U 的副本 - Michael Aaron Safyan
顺便说一下,你的 get 函数可以简化为:std::string get() { return "Hello World"; } - fredoverflow
1个回答

10

请看这个问题。C++ 标准保证一个临时变量的生命周期延续到它所在的表达式结束。因为整个函数调用是一个表达式,所以临时变量保证会持续到该函数调用表达式结束后。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接