3 ms·
> 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. Y
by 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; }.