views:

137

answers:

6

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?

+2  A: 

The local variable is destroyed when it goes out of scope. Perhaps the process is called like "going out of scope"?

Miroslav Bajtoš
+1  A: 

I'm not sure there is a name for this. Stack variables are so automatic that no one worries about them, ever, not even enough to give a name for this automatic cleanup process.

Call it "going out of scope", I guess.

wilhelmtell
+5  A: 

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.

Michael Aaron Safyan
+1  A: 

I've always heard it spoken as "going out of scope" or more precisely "an auto variable going out of scope".

msw
+1  A: 

If what you're asking is how the method call is actually implemented in machine code, I would say it would depend on the calling convention used

Tullo
+2  A: 

Stack unwinding happens in both these cases, it's just that under normal execution the stack is unwound only to the context of the calling method (or block) when the executing method returns (or the block is exited). Local variables are allocated on the stack, so they are cleaned up in reverse order of allocation, and it's this process that is called unwinding. It's no different than processing any other type of data that you'd store in a LIFO structure - e.g. undo, redo.

When an exception is thrown the handler will unwind the stack through through zero or more methods until it finds one that can catch the exception, or until it reaches the top of the stack, at which point the unhandled exception handler will be called.

It seems to be convention to only use the term stack unwinding in the case of exception handling, but it's the same process occurring in each of these cases. The specific case where the stack unwinds due to a method exiting is called returning, there doesn't seem to be any convention for naming what happens when a scoped block of code is exited.

Stu Mackellar