top | item 40029694

(no title)

mattnewport | 1 year ago

Yeah, this is one of those things that while it may be more technically correct causes a lot of unnecessary confusion. I remember being confused by this as a C++ programmer learning Java when resources claimed that Java was always pass by value where the actual behaviour in almost all cases (due to Java going almost all-in on objects) is what a C++ programmer would expect from pass by reference.

I still see even relatively experienced programmers who don't understand this, particularly working with Unity where a lot of programmers came from C++ to C# and don't realise for example that a C# function that takes a List 'by value' and modifies it is actually modifying the same instance that was passed in by the caller.

discuss

order

twic|1 year ago

No, Java really is pass by value. You can rely on this in Java:

  String s = "hello";
  foo(s);
  assert s == "hello";
In C++, if the function takes a non-const reference, you can't.

Yes, Java always passes pointers to objects. But you can pass pointers by value. And passing a pointer by value is not the same as passing by reference!

I think the origin of the confusion around a function taking a list by value and the like is the implicitness of pointers in Java and its cousins. This Java method:

  void foo(List<String> strings)
Is the equivalent of this C++ method:

  void foo(shared_ptr<List<string>> strings)
True systems languages make the pointers explicit.

mattnewport|1 year ago

That's only because strings are immutable in Java. It's not true for reference types in general.

In C++ passing a pointer by value is effectively the same as passing a reference, the only real difference being that the syntax for accessing the underlying value is more implicit for a reference.