Home > Backend Development > C++ > When Are Temporary Function Arguments Destroyed in C ?

When Are Temporary Function Arguments Destroyed in C ?

Linda Hamilton
Release: 2024-12-16 09:42:12
Original
475 people have browsed it

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));
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template