临时生命周期 [英] Lifetime of temporaries

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

问题描述

以下代码工作正常,但为什么这是正确的代码?为什么foo()返回的临时的c_str()指针有效?我想,这个临时已经销毁,当bar()进入 - 但它似乎不是这样的。所以,现在我假设foo()返回的临时将在调用bar()之后被销毁 - 这是正确的吗?为什么?

The following code works fine, but why is this correct code? Why is the "c_str()" pointer of the temporary returned by foo() valid? I thought, that this temporary is already destroyed when bar() is entered - but it doesn't seem to be like this. So, now I assume that the temporary returned by foo() will be destroyed after the call to bar() - is this correct? And why?

std::string foo() {
  std::string out = something...;
  return out;
}

void bar( const char* ccp ) {
  // do something with the string..
}

bar( foo().c_str() );


推荐答案


$ 12.2 / 临时对象
销毁作为
中的最后一步评估full-expression(1.9)
(词法)包含创建它们的点
这是真的$

$12.2/3- "Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception."

由foo返回的临时的生命周期)扩展到完整表达式的结尾,即直到函数调用'bar'结束。

The lifetime of the temporary returned by foo() extends until the end of the full expression where it is created i.e. until the end of the function call 'bar'.

编辑2:


$ 1.9 / 12-全表达式是一个
表达式,不是另一个表达式的子表达式
如果语言
构造被定义为产生
隐式调用一个函数,使用
语言构造被认为是
是一个表达式,用于定义的目的

$1.9/12- "A full-expression is an expression that is not a subexpression of another expression. If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition."

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

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