With my compiler at least, creating a reference implies no dereferencing. Therefore, code like the following works:
int trivialExample(char* array, int length)
{
char& ref = array[6];
if (length > 6)
{
std::cout << ref << std::endl;
}
}
That is, given a char array and its length (and assuming a bunch of trivialities like the array elements are all initialized and the passed length is correct), it will print the seventh character only if it actually exists.
Is this relying on undefined behavior?
Actually, this is conceptually (and practically) not different than the following:
My educated guess is that you intend to call it this way:
And in C++, as in C, just obtaining a pointer to outside of the declared array (other than the next-to-last) invokes undefined behaviour, even if not dereferenced.
The rationale is that there may be (are?) architectures that faults just by loading an invalid address in a CPU register.
UPDATE: After some research, and hints from other SO users, I’ve becomed convinced that C++ does not allow to take a reference outside of the declaring object, not even to the next-to-last element. In this particular case, the results are the same, except for the element number 6, that would be allowed in the pointer version and not in the reference one.