Home >Backend Development >C++ >How Long Do Temporary Function Arguments Live?

How Long Do Temporary Function Arguments Live?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 19:20:10505browse

How Long Do Temporary Function Arguments Live?

Lifetime of Temporary Function Arguments

When creating a temporary object as an argument to a function, the standard guarantees that its destructor will be called at the end of the full expression containing the function call.

Detailed Explanation

Temporary objects are created when a function argument is an expression that evaluates to an object. In the example provided, MyClass(42) is a temporary object.

The lifetime of temporary objects extends until the end of the full expression they are part of. A full expression typically ends at the semicolon (`;) that concludes the statement containing the expression. In this case, the full expression ends with the closing parenthesis of the function call to myFunction().

Therefore, the destructor of the temporary MyClass object created in MyClass(42) will be called before execution proceeds to the next statement after the function call.

Extending Temporary Lifetime

While temporary objects are generally short-lived, their lifetime can be extended by binding them to a constant reference. For instance:

const MyClass& r = getMyClass();

In this case, the temporary object returned by getMyClass() will persist until the end of the enclosing block, extending its lifetime beyond the full expression.

The above is the detailed content of How Long Do Temporary Function Arguments Live?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn