Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is destroying local variables when a block is exited normally called in C++?

C++ automagically calls destructors of all local variables in the block in reverse order regardless of whether the block is exited normally (control falls through) or an exception is thrown.

Looks like the term stack unwinding only applies to the latter. How is the former process (the normal exit of the block) called concerning destroying local variables?

like image 872
sharptooth Avatar asked Apr 09 '10 05:04

sharptooth


People also ask

What happens to the local variables when the method is exited?

Local variables are created on the call stack when the method is entered, and destroyed when the method is exited.

Do local variables get destroyed?

Local variables are destroyed in the opposite order of creation at the end of the set of curly braces in which it is defined (or for a function parameter, at the end of the function).

Are local variables deallocated?

The local variables that are allocated on stack, i.e. without using memory allocation functions or operators like malloc and new , are deleted automatically. All other variables have to be deleted by using delete as they are stored on heap. Simply explained.

Is static and local variable are same?

A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared, e.g. to be used as a count variable.


1 Answers

An object is automatically destructed when it "goes out of scope". This could be referred to as "automatic storage reclamation", but that actually refers to garbage collection (there are several papers with that phrase in their name that use the term to mean garbage collection). When it is used to ensure proper pairing of open/close, lock/unlock, or other forms of resource acquisition with their appropriate release, then it is known as the design pattern of Resource Acquisition is Initialization (RAII), which is somewhat ironic given that the main aspect of RAII is not the resource initialization or acquisition, but rather its destruction.

like image 142
Michael Aaron Safyan Avatar answered Sep 19 '22 05:09

Michael Aaron Safyan