Temporary Object Destruction in C
One might wonder when temporary objects, created by value arguments to function calls or constructors, are destroyed. The precise timing of their demise is crucial for determining the correct execution of code involving temporarily allocated entities.
To illustrate the issue, consider the following example:
#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'; }
Would this code print "one, two, three"? Not necessarily. The behavior depends on the C compiler and the particular settings used for compilation.
According to the C standard ([class.temporary] p4), a temporary object's lifetime lasts until the end of the full expression it was created in. In the provided example, the full expression is the entire main function. Therefore, the destruction of the temporary Foo objects occurs at the end of main, which conforms to the observed printing sequence.
However, [class.temporary] p5, p6, and p7 define several exceptions to this general rule. For example, the lifetime of temporary objects in the initialization of arrays can be shortened. Additionally, binding a reference to a temporary object or using it in a for-range-initializer can extend its lifetime.
In conclusion, the precise timing of temporary object destruction in C is governed by the standard. While in most cases, temporaries are destroyed at the end of the expression that created them, certain exceptions and compiler optimizations can alter this behavior. understanding these nuances is essential for writing correct and predictable C code.
The above is the detailed content of When Are Temporary Objects in C Destroyed?. For more information, please follow other related articles on the PHP Chinese website!