3 ms·
C also has only pass-by-value semantics. The difference is that you can take the address of a variable, i.e. you can stack as many layers of references as you w
by Asooka 9y ago
C also has only pass-by-value semantics. The difference is that you can take the address of a variable, i.e. you can stack as many layers of references as you want. In case of the C++ swap:
template<class T>
void swap(T& a, T& b) {
T tmp = a;
a = b;
b = tmp;
}
When called as
int a=1, b=2;
swap(a, b);
The variables a and b are passed by reference, or you can think of it as an implicit pointer. This is the meaning of pass-by-reference - changes made to the value of a variable directly impact the referred-to variable.
Pass-by-reference can be confusing and its inclusion in C++ is useful as immutable non-null pointers, a use which modern languages support in various other ways. Thinking of Java objects as pointers to objects might be a bit confusing at first as well, but it's the correct mental model for what's happening under the hood.
It all goes back to understanding computation in the context of a von Neumann machine with addressable random-access memory, and knowing that values are stored in numbered memory cells, so variables can be either the memory region itself, the memory region's number, which itself can be stored in a memory region whose number can be stored in another ... etc. You can't abstract away the basic properties of the computing architecture we use, so it's a good idea for programmers to have mental models of computer memory and programming language variables that are fundamentally congruent with the von Neumann architecture.
- kazinator 9y ago> Pass-by-reference can be confusing and its inclusion in C++ is useful as immutable non-null pointers You can easily bind a C++ reference to a null pointer. Your compiler will silently accept it and the behavior will be predictably that &ref == 0 will evaluate true. E.g. // if OOM, &ref is null object &ref = *new (std::nothrow) object(args, ...); Of course, it's not defined behavior; i.e. wrong on paper. (If only a paper tiger could defend you against a real flesh-and-horn charging rhinoceros, ...) Whether or not it's defined is moot; the fact is you can commit undefined behavior with references. They are just pointers in disguise: wolves clad in sheepskins. References inside class/struct objects are real pointers occupying a word. If such an object is out of scope and has been deleted, and you use the reference, it's exactly the same as a use-after-free of a pointer or any other value. Through the bad reference, some wrong object will be accessed or modified. The only relatively harmless references are the lexicaly scoped ones which go away at compile time, behaving as aliases: { int x = 42, &x_alias = x; }.