Who modified my local variable?

Michael L Torrie torriem at chem.byu.edu
Tue Jun 13 13:11:10 MDT 2006

On Tue, 2006-06-13 at 12:47 -0600, Bryan Sant wrote:
> C++:
> void no_leak() {
>   MyObject obj(1, 2, 3);
> }
> Local variable.  Allocated on the stack.  Falls out of scope shortly.  No leaks.
> 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.

Sure.  But my real point was the Java habit of always doing "new" causes
a ton of problems for Java programmers heading into C++.  Rather than
use a local variable allocated on the stack, they do "new" which leaks.
That is the problem.  So really it's not a language problem; it's a
programmer problem.  But a programmer can be trained; unfortunately Java
is not a good trainer in this instance.  In my opinion it would be
better to subject a new CS student to C and C++ in all their glory and
then introduce them to managed, Garbage-collected languages later,
rather than the other way around.

So your point below about cost of allocations is besides the point.  

> 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
> /*
> PLUG: http://plug.org, #utah on irc.freenode.net
> Unsubscribe: http://plug.org/mailman/options/plug
> Don't fear the penguin.
> */

More information about the PLUG mailing list