Automatic Objects: Destructed in reverse order of definition, when the enclosing scope concludes.
Non-Local Static Objects: Destructed in reverse order of definition, after execution of main (global variables, static member data).
Local Static Objects: Constructed the first time control flow passes their definition, and destructed in reverse order after execution of main (static variables within functions).
Destructed in reverse order of definition, first member subobjects, then base class subobjects.
Destructed in descending order. If an exception occurs during construction of the n-th element, elements n-1 to 0 are destructed first.
Constructed when prvalue expressions of class type are evaluated. Destructed when the containing expression completes evaluation. If an exception occurs during evaluation, temporary objects are correctly destructed.
Dynamic Objects: Allocated with new Foo and destructed with delete p.
Dynamic Arrays: Allocated with new Foo[n] and destructed with delete[] p.
In both cases, attempting to destroy the memory multiple times, accessing after destruction, or using incorrect destruction mechanisms (e.g., delete[] for single objects) results in undefined behavior. If an exception occurs during construction, dynamically allocated memory is released before the exception propagates.
std::shared_ptr
Exception Behavior:
Destructors should never throw exceptions as this can terminate the program. If an exception occurs during object destruction, it is propagated and all previously destructed subobjects are correctly destructed. However, if a dynamic object's exception occurs during construction, memory is released before the exception propagates, and the object's destructor is not called.
The above is the detailed content of How Are Objects Destroyed in C ?. For more information, please follow other related articles on the PHP Chinese website!