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';
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:
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!