Destruction of Temporary Objects in C
Considering the following code:
#include <iostream> struct Foo { const char* m_name; ~Foo() { std::cout << m_name << '\n'; } }; int main() { Foo foo{"three"}; Foo{"one"}; // unnamed object std::cout << "two" << '\n'; }
It's evident that the output will be "one", "two", and "three." This raises the question: is this behavior guaranteed across all C compilers?
According to the C standard, in [class.temporary], it states:
"Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created."
This rule implies that temporary objects, such as the unnamed Foo object in the provided code, will be destroyed at the end of the full expression in which they were created, i.e., the semicolon at the end of the line.
It's important to note that there are exceptions to this general rule, outlined in [class.temporary] p5, p6, and p7:
However, in the provided code, none of these exceptions apply, ensuring the guaranteed destruction of temporary objects at the end of their respective expressions.
The above is the detailed content of Is the Destruction Order of Temporary Objects Guaranteed in C ?. For more information, please follow other related articles on the PHP Chinese website!