Temporary Object Destruction in C
When do temporary objects in C get destroyed? This question arises when considering the following code snippet:
#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'; }
The code prints "one," "two," and "three." This behavior might seem unexpected if temporary objects were destroyed immediately after their creation. However, that is not the case.
Temporary objects, as defined in [class.temporary] p4, are destroyed at the end of the full expression containing the point where they were created. In the example above, the full expression is the entire main function, so the temporary Foo objects are destroyed at the semicolon.
This behavior is standard-guaranteed, making the output of the given code consistent across C compilers. However, there are some exceptions to the general rule:
The above is the detailed content of When Do Temporary Objects in C Get Destroyed?. For more information, please follow other related articles on the PHP Chinese website!