Object Destruction in C
Object Destruction: What, When, and How
In C , objects can be broadly classified as scoped objects and dynamic objects. Scoped objects have a lifespan tied to their enclosing scope (e.g., local variables, global variables, class instances), while dynamic objects are created and destroyed using pointers (e.g., new, delete).
Scoped Objects
-
Automatic Objects: Destroyed in reverse order of creation as control flow exits their scope (e.g., function exit, end of a block).
-
Non-local Static Objects: Destroyed in reverse order of creation after main() execution.
-
Local Static Objects: Constructed when control flow enters their definition for the first time and destroyed in reverse order after main() execution.
-
Base Class and Member Subobjects: Destroyed in reverse order within an object's destructor, followed by its base class subobjects.
-
Array Elements: Destroyed in descending order.
-
Temporary Objects: Created from prvalue expressions, destroyed when the full expression is evaluated.
Dynamic Objects
- Dynamic Objects (new Foo): Destroyed by explicitly calling delete p.
- Dynamic Arrays (new Foo[n]): Destroyed by explicitly calling delete[] p.
Exception Handling
- Exceptions are propagated back through the stack, calling destructors on previously created automatic objects.
- Destructors should never throw exceptions.
- If an exception occurs during object construction, the underlying memory is released before the exception is thrown.
Manual Object Destruction
Since C lacks a garbage collector, dynamic objects must be manually released to prevent resource leaks.
Smart Pointers
-
Reference-Counting Smart Pointers (std::shared_ptr): Automatically destroy the underlying object when the last std::shared_ptr referencing it is destroyed.
The above is the detailed content of How Does Object Destruction Work in C ?. For more information, please follow other related articles on the PHP Chinese website!