Home >Backend Development >C++ >When Are Temporary Function Arguments Destroyed in C ?
Temporary Function Arguments: Destruction Timing
When creating temporary objects as function arguments, managing their lifetime is crucial for program correctness. C dictates the lifetime of these temporaries.
In the example provided:
class MyClass { MyClass(int a); }; myFunction(MyClass(42));
C guarantees that the destructor for the temporary MyClass object is called at the end of the full expression that the object is part of. A full expression typically ends at the semicolon ; or other statement terminators. In this case, the full expression ends at the closing parenthesis of the function call myFunction().
Therefore, you can assume that the temporary object's destructor will be called before the execution of the next statement following the function call.
Note that extending the lifetime of temporaries beyond the full expression is possible by binding them to a const reference. This extends their lifetime to the reference's lifetime, as illustrated in the following example:
MyClass getMyClass(); { const MyClass& r = getMyClass(); // full expression ends here ... } // object returned by getMyClass() is destroyed here
The above is the detailed content of When Are Temporary Function Arguments Destroyed in C ?. For more information, please follow other related articles on the PHP Chinese website!