3 ms·
If you don't understand that it's pass by value of references for non-primitives then... Right: pass by value, of references. That's the complete answer, and
by ewjordan 17y ago
If you don't understand that it's pass by value of references for non-primitives then...
Right: pass by value, of references. That's the complete answer, and it's really misleading to say anything else.
I don't think any Java programmers actually have any misunderstanding here, even the worst of them know how this works. What's the problem?
Also, the article tries to use code like this:
void swap(SomeType& arg1, Sometype& arg2) {
SomeType temp = arg1;
arg1 = arg2;
arg2 = temp;
}
to prove how different references in C++ are from Java.
But the reason something like that might work in C++ is not that the semantics of parameter passing are different (references cannot be reseated in C++ any more than in Java), but that C++ uses the assignment operator to overwrite the contents of the lhs, and invokes the copy constructor automatically. The true equivalent code in Java works just fine, assuming the copy constructor and set method do the right things (which is a potential pitfall in C++, as well):
static public void swap(SomeType arg1, SomeType arg2) {
SomeType temp = new SomeType(arg1);
arg1.set(arg2);
arg2.set(temp);
}
- tedunangst 17y agoSomeType could be a primitive type. Your java code won't work for int or float or Object * (if you could have such a thing).
- ewjordan 17y agoRight, but that's more a statement about Java's quirky treatment of primitives than anything else - those are certainly passed by value, but nobody has ever argued anything else. The only confusion/argument is over whether Object types are passed by value or by reference, and it's massively misleading to say they're passed by value, since if you don't know the rest of the story, you'll write code that doesn't run correctly. The only reason that code won't work for Object is that you can't add a copy constructor or "set" method to Object, not because of any difference in reference semantics. In a real-world implementation we might try to simulate duck-typing by accepting an Object and using reflection to check for the appropriate methods on the object, and though it would be a bit slow it would work for any object type that had the methods defined. My main point was that for any type SomeType that lets the Java code compile, it will do exactly the same thing as the analogous code does in C++, assuming you've defined the class methods appropriately. Which makes it a very poor illustration of the difference between reference semantics in Java and C++.
- deleted 17y ago[deleted]