c++ - 临时变量的生命范围

标签 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下测试过了。两者都适用。

最佳答案

参见 this question .该标准保证临时文件一直存在到它所属的表达式结束为止。由于整个函数调用都是表达式,因此临时对象可以保证一直持续到它作为其中一部分的函数调用表达式结束之后。

关于c++ - 临时变量的生命范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3041959/

相关文章:

c++ - 为什么这个功能进入范围?

c++ - 在 C++ 中包含 OpenCV for Project

c# - 使用 memcpy 从 C++ 到 C#

c++ - Next_permutation 和效率

c# - 将结构列表从 C# 转换为 C++

即使在堆上,C++ 程序也会因数组过大而崩溃

c++ - 如何使用 Poco C++ 从 HTTP 服务器响应中读取图像内容?

c++ - 运算符重载c++将int添加到对象

c++ - C++ 中的错误消息 "Undefined reference error to"

c++ - Boost进程间共享内存删除、权限和输出文件