Home >Backend Development >C++ >How Long Do Temporary Function Arguments Live in C ?
Understanding the Lifetime of Temporary Function Arguments
When utilizing temporary objects instantiated as function arguments, as exemplified below:
class MyClass { MyClass(int a); }; myFunction(MyClass(42));
It's crucial to understand the behavior of their destruction. The C standard provides insights into the timing of their destructors.
Destruction Timing of Temporary Arguments
Temporary objects meet their end at the conclusion of the complete expression they inhabit. A complete expression denotes an expression that stands alone, not nested within another. Typically, this corresponds to the semicolon (or closing parenthesis for conditional, loop, and switch statements) designating statement completion. In the given example, the complete expression terminates with the function call.
Prolonging Temporary Lifespan
It's noteworthy that the lifetime of temporaries can be extended by referencing them as a constant reference. This strategy extends their lifespan to match that of the reference:
MyClass getMyClass(); { const MyClass& r = getMyClass(); // full expression ends here ... } // object returned by getMyClass() is destroyed here
Using this technique can optimize performance by avoiding an unnecessary copy constructor invocation compared to using MyClass obj = getMyClass();. However, its prevalence is somewhat low.
The above is the detailed content of How Long Do Temporary Function Arguments Live in C ?. For more information, please follow other related articles on the PHP Chinese website!