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.
C++:
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?
Java:
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:
http://www-128.ibm.com/developerworks/library/j-jtp01274.html
Teaser Quote from article:
"The JIT compiler can perform additional optimizations that can reduce
the cost of object allocation to zero."
-Bryan