%s\n", c); } std::string get() { s-6ren">
gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:21 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com