4 ms·
> In C code, you'll find many uses of pointers for iteration, which can't be replaced with C++ references. In c++, ranged for loops are both far more common an
by usefulcat 4y ago
> In C code, you'll find many uses of pointers for iteration, which can't be replaced with C++ references.
In c++, ranged for loops are both far more common and idiomatic for iteration, and will compile to the most efficient form possible. At least for gcc and clang, you definitely don't have to 'hope' that they will be optimized to the equivalent pointer-based code--they will be.
> ... whereas at least with pointers you can always check in your own code.
Regarding null references -- the only way for that to happen is by dereferencing a null pointer, which of course is equally invalid with or without references.
BUT: if all you have is pointers, then--all else being equal--you will have many more places where you may need to check whether a pointer is null.
Once you've converted a pointer to a reference by dereferencing it, you (and the compiler) can legitimately assume that it's never null. If you ever encounter a 'null reference', the problem is never with the reference, it's always guaranteed to be with a deference somewhere higher up the stack. As a result, when references are available and preferred, there are not nearly as many places where you have to decide whether to check for null in the first place.