Who modified my local variable?

Bryan Sant bryan.sant at gmail.com
Tue Jun 13 12:47:33 MDT 2006

On 6/13/06, Michael L Torrie <torriem at chem.byu.edu> wrote:
> I'm not quite using my terms right.  As you say, a static thing is
> generally something that is allocated once and only once.  I'm talking
> about something different.  In C++ you can allocate objects in a non-
> dynamic fashion (ie "ClassName instance(blah)") and it is allocated on
> the stack, not the heap, and has a strictly controlled lifetime.
> Because of this the likelihood of a leak is much reduced.


void no_leak() {
  MyObject obj(1, 2, 3);

Local variable.  Allocated on the stack.  Falls out of scope shortly.  No leaks.

> How do you statically allocate on the stack a more complicated object
> that requires several parameters in the constructor?


void noLeak() {
  MyObject obj = new MyObject(1, 2, 3);

Local variable.  Sometimes called an automatic variable in Java-terms.
 Allocated on the heap (which is really just a stack in the case of
auto vars).  Falls out of scope shortly.  GC will pop this off the
heap-stack-thingy.  No leaks.

Same result and almost the same technique is used by the both the C++
and Java runtimes.

Read the first part of this article for more info on Java GC:

Teaser Quote from article:
"The JIT compiler can perform additional optimizations that can reduce
the cost of object allocation to zero."


More information about the PLUG mailing list