临时变量的寿命范围 [英] Life Scope of Temporary Variable

查看:100
本文介绍了临时变量的寿命范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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测试了这个。

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.

推荐答案

请参阅。该标准保证临时生命,直到其作为其一部分的表达式的结束。由于整个函数调用是表达式,所以临时函数保证持续到函数调用表达式结束之前,在函数调用表达式中它是它的一部分。

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.

这篇关于临时变量的寿命范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆