问题描述
当创建 MyClass 的新实例作为函数的参数时:
When creating a new instance of a MyClass as an argument to a function like so:
class MyClass { MyClass(int a); }; myFunction(MyClass(42));
标准是否让任何受赠方了解析构函数的时间?
,我可以假设它将在调用 myFunction()之前的下一个语句之前被调用?
does the standard make any grantees on the timing of the destructor?
Specifically, can I assume that the it is going to be called before the next statement after the call to myFunction() ?
推荐答案
临时对象在它们所属的完整表达式的末尾被销毁。
Temporary objects are destroyed at the end of the full expression they're part of.
完整表达式是不是某个其他表达式的子表达式的表达式。通常这意味着它以; (或)结束 if , while , switch 等)。在你的例子中,它是函数调用的结束。
A full expression is an expression that isn't a sub-expression of some other expression. Usually this means it ends at the ; (or ) for if, while, switch etc.) denoting the end of the statement. In your example, it's the end of the function call.
请注意,您可以通过将临时表的生命周期绑定到 const 引用来延长它们的生命周期。这样做会将其生命周期延长到引用的生命周期:
Note that you can extend the lifetime of temporaries by binding them to a const reference. Doing so extends their lifetime to the reference's lifetime:
MyClass getMyClass(); { const MyClass& r = getMyClass(); // full expression ends here ... } // object returned by getMyClass() is destroyed here
如果你不打算改变返回的对象,这是一个不错的技巧来保存一个复制构造函数调用(与 MyClass obj = getMyClass() code>),以防未应用返回值优化。不幸的是,它不是很知名。 (我想,C ++ 11的移动语义将会使它更少的有用,虽然。)
If you don't plan to change the returned object, then this is a nice trick to save a copy constructor call (compared to MyClass obj = getMyClass();), in case return value optimization was not being applied. Unfortunately it isn't very well known. (I suppose C++11's move semantics will render it less useful, though.)
这篇关于C ++:临时参数的生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!