Home > Backend Development > C++ > When are Temporary Objects Destroyed in C ?

When are Temporary Objects Destroyed in C ?

Barbara Streisand
Release: 2024-11-12 17:34:02
Original
320 people have browsed it

When are Temporary Objects Destroyed in C  ?

Temporary Object Destruction in C

In C , temporary objects are created on demand during the evaluation of expressions. These objects exist only within the scope of the expression and are automatically destroyed after it concludes.

Consider the following example with three code lines:

Foo foo{"three"};
Foo{"one"};
std::cout << "two" << '\n';
Copy after login

The code prints "one," "two," and "three" in that order. This behavior arises from the following rules governing temporary object destruction:

Destruction at End of Expression Evaluation

Temporary objects are destroyed upon the completion of evaluating the full expression in which they were created. In this example, the temporary objects for "one" and "three" are destroyed after the respective lines they reside in.

Exceptions to the Rule

While temporary object destruction typically follows this rule, specific exceptions exist, as outlined in [class.temporary] p4-p7:

  1. Shortened lifetime of default-constructed temporary objects in array initializers.
  2. Shortened lifetime of default constructor arguments during array copying.
  3. Extended lifetime of temporary objects by binding a reference to them.
  4. Extended lifetime of temporary objects in a for-range-initializer.

In the provided example, none of these exceptions apply, so the temporary objects are destroyed after their respective lines, resulting in the specified output.

The above is the detailed content of When are Temporary Objects 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