On Tue, 13 Jun 2006 at 09:13 -0600, Bryan Sant wrote: > On 6/12/06, Michael L Torrie <[EMAIL PROTECTED]> wrote: > >Methinks Java's implicit pass by reference, and > >apparent lack of statically allocated objects, has poisoned a lot of > >programmers thinking. > > What? No mention of C# or a zillion other 4GL that do the same thing > :-)? When moving back and forth between Java and C++ this is an > oddity. Or if you learned to program in Java, but are writing > something in C++, you'll expect things to work differently (wrongly > from a C++ programmers perspective). I agree that this can get > naughty. > > But just to clear things up. Java doesn't pass by reference > implicitly. It ALWAYS passes by value. So when you pass any > primitive value, it works just like you would expect in C/C++ -- it > makes a copy of the var passed into a function (be it a byte, char, > short, int, double, etc.). However, when you pass an object REFERENCE > into a function, it happily copies the reference (4-byte pointer on a > 32-bit arch) and does not make a wasteful memory copy of object data + > vtable pointers. And since the Java heap + garbage collector works > essentially like a stack, you always get the benefit of a stack even > when allocating on the "heap". It's not quite that simple, there's a > lot of multi-generational GC magic, but it's typically that > efficient. Anyway, when dealing with all but the most trivial > objects/structs in C/C++ you typically pass those objects around by > reference or pointer anyway. So the approach in Java and C++ really > isn't that different after all. > > BTW if you really want a copy of an object, you can use a copy > constructor, or implement the clone() method.
Java's way of doing it was initially a stumbling block for me and others coming from C, but I do like it more now. It's the same in ruby, which is where I grew attached to it. You just think of it as passing "the object" around unless you explicitly duplicate or clone. This is, I think, the common case, and saves a lot of headache with forgotten * or & sprinkled throughout your C++ code. I'm doing some intense C++ this summer, and this is one of the things that has really stuck out like a sore thumb. -- Hans Fugal ; http://hans.fugal.net There's nothing remarkable about it. All one has to do is hit the right keys at the right time and the instrument plays itself. -- Johann Sebastian Bach
signature.asc
Description: Digital signature
/* PLUG: http://plug.org, #utah on irc.freenode.net Unsubscribe: http://plug.org/mailman/options/plug Don't fear the penguin. */
