tags:

views:

264

answers:

4

because obj, the playingCard object is created inside a nested for loop does that mean after the second for loop completes, obj gets deallocated from the stack each time?

and a small side question, does a compiler use the stack (similar to recursion) to keep track of loops and nested loops?

    for(int c = 0;c<nElems;c++) {
 for(int z = c + 1;z<nElems;z++) {
      playingCard obj;


  }
 }
+2  A: 

It gets allocated/deallocated on every iteration of your inner loop.

I'm not clear on your side question, but the compiler uses the stack to keep track of all local variables that it can't otherwise just squeeze into registers.

Jim Buck
Variables on the stack are not usually allocated/deallocated for every iteration (I'm sure a compiler COULD implement it's variable storage in such a way, but it would be somewhat silly.) The variable is allocated on the stack once, and it's constructor is called at the entry of every loop and destructor at the end of every loop. It most likely will not be deallocated until the function returns.
Falaina
Yeah, by alloc/dealloc, I actually mean the object gets constructed/destructed (which is what I think the OP meant by "obj gets deallocated"). The physical memory itself just stays in place most likely.
Jim Buck
+2  A: 

The scope of the object is in with-in the enclosing braces [ whether it is a function or loop brace ]. so, as soon as the scope ends, the destructor of the object gets called and the object gets deallocated.

Coming to your second question, depends on the compiler to maintain its own strategy to handle the loops and keep track of the objects.

Roopesh Majeti
+1  A: 

Objects in the stack are allocated or deallocated once (even if they are nested in loops).
However, constructors and destructors are called on every iteration.

Nick D
+4  A: 

It gets constructed and deconstructed every iteration.

However, on the stack, the concept of allocation is (for at least VS and GCC) more hazy. Since the stack is a contiguous block of memory, premanaged by the compiler, there's no real concept of allocating and deallocating in the way that there is for heap allocations (new/delete or malloc/free). The compiler uses the memory it needs on the stack, and simply rolls back the pointer later on.

Dave Gamble
+1 for talking about why allocation/dealloction on the stack is tricky. Although, in general, it's fair to say any region of memory above the stack pointer is allocated, and memory below it is unallocated (There are obviously exceptions to this :) ).
Falaina