这里的临时字符串的寿命够长吗
Is the lifetime of the temporary string long enough here?
#include <cstdio>
#include <string>
std::string foo()
{
return "Hello, World!";
}
int main()
{
printf( "%sn", foo().c_str() );
}
是的,它足够长了。当函数返回时,字符串文字将不存在,但此时它已被复制到临时std::string
。该字符串将被复制(或将通过复制省略在调用站点创建)到调用代码。生成的字符串将一直存在到表达式结束,其长度足以传递给printf
。
return "Hello, World!";
返回一个由c样式字符串文字构造的std::string
(隐含地),在函数的作用域中可以被视为static
在这种情况下,从foo()
返回后,临时std::string
的寿命可以被认为是稳定的。它将被复制,或者至少被更现代的标准实现移动。