且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++:临时参数的生命周期?

更新时间:2023-01-25 17:16:56

临时对象在它们所属的完整表达式的末尾被销毁。

Temporary objects are destroyed at the end of the full expression they're part of.

完整表达式是不是某个其他表达式的子表达式的表达式。通常这意味着它以; $ c>(或结束 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.)