4 ms·
While C++ is a whole lot of different language with operator overloading amd everything, I don't think the pass-by-reference in the C++'s way with &'s before th
by ThoAppelsin 8y ago
While C++ is a whole lot of different language with operator overloading amd everything, I don't think the pass-by-reference in the C++'s way with &'s before the variable/parameter identifiers is much different from how Java handles the objects behind the curtains.
In Java with no explicit pointers available to its users, the way objects are handled are explained better with the pass-by-reference concept than (whooosh!, magic in) pointers (and out) passed-by-value reality. Pointer is a foreign concept to Java, so it really makes more sense to its users that object variables start referring to other objects when they are reassigned, instead of the old object being changed in-place. Things get funky with equality comparison via == operator, but still, it is better than pointers.
I also wonder, does C++ really pass-by-reference when parameters have &'s behind their identifier declarations, or does it internally pass a reference by value and dereference it every time it is used within that scope? Are 4/8 bytes allocated for the reference variable or not?
- colanderman 8y agoNo, it really is different. In C++ you can assign to variable references without additional syntax. You cannot do this (at all) in Java. I don't know what you mean by "really pass-by-reference". There is no such concept of a "reference" at the CPU level; nor is that relevant to language semantics. If you were to look at the generated assembly it would look identical to as if pointer referencing and dereferencing were used.
- ThoAppelsin 8y ago> I don't know what you mean by "really pass-by-reference". I was wondering if `int &a2 = a;` allocates memory in stack to make `a2` refer to `&a`, or does `a2` somehow truly become an alias for `a` in symbol table. As you've said that the assembly would look the same as pointers being dereferenced, then I suppose C++'s reference types are just a syntax sugar around the C's way of achieving the pass-by-reference concept through passing the address and then dereferencing it.
- chi3 8y agoUnless I'm misunderstanding you, what you're asking is only possible in a function signature if the compiler inlines it. However, outside of function signatures, if you write: int a = 2; int &aref = a; int b = aref; I'd assume that the compiler is smart enough to optimize away &aref.