临时体的完整表达边界和寿命
可能的重复:
临时函数参数的生命周期是多少?
临时对象何时销毁?
据说临时变量是在评估完整表达式的最后一步被销毁的,例如
bar( foo().c_str() );
临时指针一直存在,直到 bar 返回,但是
baz( bar( foo().c_str() ) );
它仍然存在直到 bar 返回,或者 baz return 意味着完整表达式结束,这是为了什么, 我检查了编译器在 baz 返回后析构对象,但我可以依赖它吗?
Possible Duplicate:
What is the lifetime of temporary function arguments?
When are temporary objects destroyed?
It is said that temporary variables are destroyed as the last step in evaluating the full-expression, e.g.
bar( foo().c_str() );
temporary pointer lives until bar returns, but what for the
baz( bar( foo().c_str() ) );
is it still lives until bar returns, or baz return means full-expression end here,
compilers I checked destruct objects after baz returns, but can I rely on that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
临时对象一直存在到创建它们的完整表达式结束为止。 “完整表达式”是不是另一个表达式的子表达式的表达式。
在
baz(bar(...));
中,bar(...)
是baz(...)
的子表达式, whilebaz(...)
不是任何内容的子表达式。因此,baz(...)
是完整表达式,并且在baz(...)
返回之前,在此表达式求值期间创建的所有临时变量都不会被删除。Temporaries live until the end of the full expression in which they are created. A "full expression" is an expression that's not a sub-expression of another expression.
In
baz(bar(...));
,bar(...)
is a subexpression ofbaz(...)
, whilebaz(...)
is not a subexpression of anything. Therefore,baz(...)
is the full expression, and all temporaries created during the evaluation of this expression will not be deleted until afterbaz(...)
returned.顾名思义,完整表达式是所有表达式,包括对
baz()
的调用,因此临时表达式将一直存在,直到对baz()
的调用返回。As the name suggests, the full-expression is all of the expression, including the call to
baz()
, and so the temporary will live until the call tobaz()
returns.