4 ms·
> (If they passed by reference, you could change to which value a caller's variable was bound, like you can in C++) I might be misunderstanding you, but I don'
by alexhutcheson 8y ago
> (If they passed by reference, you could change to which value a caller's variable was bound, like you can in C++)
I might be misunderstanding you, but I don't think you can do this in C++. References can't be changed to point to a different object after initialization. If you have code like:
void MyFunc(Foo& ref_param) {
Foo new_foo;
ref_param = new_foo;
}
The assignment above isn't "changing the value to which a caller's variable is bound". Instead, it's running the '=' operator on the Foo object to copy the state from new_foo to ref_param. To demonstrate this, you could run the following to see that the addresses are the same:
Foo original_object;
Foo& object_ref = original_object;
MyFunc(object_ref);
// object_ref still points to the same address
assert(&original_object == &object_ref);
Under the hood, C++ reference params are basically syntactic sugar for passing by pointer-value, so this behavior isn't surprising.
- colanderman 8y agoThe proper analogy for a Python object is `std::shared_ptr<Foo>`: in Python, all "objects" are actually reference-counted pointers to objects (thus making them shareable). And then yes, in C++, you can change to which object the caller's "object" (pointer-to-object) points to, if you pass a reference to that. This is not possible in Python: all you can do is pass that shared-pointer value around, not the value of the object itself, nor a reference to the shared pointer. This is a well-known distinction that goes by several names, see e.g. https://en.m.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing https://en.m.wikipedia.org/wiki/Evaluation_strategy#Call_by_...
- alexhutcheson 8y agoAh, got it. Your basic point is that C++ params can use two layers of indirection (pointer-to-ref, ref-to-pointer, pointer-to-pointer, etc.), while doing so in Python is clunky. Makes sense.