Home >Backend Development >C++ >Why Are Temporary Objects Destroyed in a Surprising Order in C ?
Temporary Object Destruction in C
The provided code demonstrates a surprising behavior where temporary objects are destroyed in an unexpected order. However, this behavior is actually guaranteed by the C standard.
Explanation
Temporary objects, which are also known as unnamed objects, are created when an expression evaluates to a class type that is not a reference type. They are typically used to hold intermediate results during an expression's evaluation.
In the given code, a temporary object of type Foo is created from a character string literal, and its destructor is invoked when the object's lifetime ends. The destructor prints the name stored in the object's m_name member.
The lifetime of a temporary object ends at the end of the full expression it was created in. In the provided code, the full expression is the statement:
Foo{ "one" };
Therefore, the temporary object's lifetime ends at the semicolon following this statement. As a result, the destructor of the temporary object is invoked, and the string "one" is printed.
Exceptions to the Rule
While the general rule dictates that temporary objects are destroyed at the end of the full expression, there are a few exceptions specified in the C standard ([class.temporary] p5-p7):
These exceptions allow for more flexibility in managing the lifetime of temporary objects in specific situations.
The above is the detailed content of Why Are Temporary Objects Destroyed in a Surprising Order in C ?. For more information, please follow other related articles on the PHP Chinese website!