Home > Backend Development > C++ > How Are Objects Destroyed in C ?

How Are Objects Destroyed in C ?

Barbara Streisand
Release: 2024-12-10 09:45:12
Original
706 people have browsed it

How Are Objects Destroyed in C  ?

Object Destruction in C

Scoped Objects

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).

Base Class and Member Subobjects:**

Destructed in reverse order of definition, first member subobjects, then base class subobjects.

Array Elements:**

Destructed in descending order. If an exception occurs during construction of the n-th element, elements n-1 to 0 are destructed first.

Temporary Objects:**

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 and Arrays:**

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.

Reference-Counting Smart Pointers:**

std::shared_ptr: Destructs the managed object as the last std::shared_ptr object referencing it is destructed.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template