views:

49

answers:

1

I know a compiler may detect life-time of different variables of a function and use the same stack frame slot for some different variables if it detects at beginning of life-time of each one of them life-time of previous variables has ended; but in case of local objects of classes in a function may it analyze life-time of members individually and say like since at this point life-time of this specific data member is finished let's use this part of stack frame memory for something else or it just does this for whole object as an atomic entity, what about objects of unions, would there be such analysis for those?

+1  A: 

The lifetime of an "automatic" (local and non-static) C++ variable (object named in declaration) is simple: from the point of declaration to the end of the innermost enclosing block. A block is a pair of curly braces, {,,,}. So, the lifetimes are strictly nested, and no special analysis is needed to determine them.

So far, we're within what the C++ standard specifies.

When talking about "stack frames" we're outside of the standard, into implementation details. Local variables form a "stack" in the computer science sense of Last In First Out allocation/deallocation, and that computer-science-sense "stack" can be and most often is implemented in terms of the computer's very much more concrete "machine stack" (just a contiguous area of memory). But it doesn't need to be. And C++ compilers have existed that produced code that didn't use the machine stack.

Assuming use of a machine stack, there's no such thing as a stack "slot".

The machine stack is just bytes, or on a word-addressed machine, words.

The main way that compilers are smart about using the machine stack is when a function has several calls to other functions, and those other function have C call convention. With C call convention the caller pushes items on the stack, and it's also the caller that pops them. And instead of all those push and pop operations the compiler can arrange to have a suitable amount of stack space available for the call that requires the most, and just place arguments where they're needed, not bothering with adjusting the stack pointer.

OK, you'll have to look up 'push', 'pop' and 'stack pointer', e.g. in Wikipedia. But I doubt you'll find the explanation above in Wikipedia. One compiler that does this is g++, and you can use the g++ option to produce an assembly listing to see what's going on -- with a suitable test program, of course.

Cheers & hth.,

Alf P. Steinbach