The following code fools around with nullptr
pointer and reference:
#include <cstdio>
void printRefAddr(int &ref) {
printf("printAddr %p\n", &ref);
}
int main() {
int *ip = nullptr;
int &ir = *ip;
// 1. get address of nullptr reference
printf("ip=%p &ir=%p\n", ip, &ir);
// 2. dereference a nullptr pointer and pass it as reference
printRefAddr(*ip);
// 3. pass nullptr reference
printRefAddr(ir);
return 0;
}
Question: In C++ standards, are commented statements 1..3 valid code or undefined behavior?
Is this same or different with different versions of C++ (older ones would of course use 0
literal instead of nullptr
keyword)?
Bonus question: are there known compilers / optimization options, which would actually cause above code to do something unexpected / crash? For example, is there a flag for any compiler, which would generate implicit assertion for nullptr
everywhere where reference is initialized, including passing reference argument from *ptr
?
An example output for the curious, nothing unexpected:
ip=(nil) &ir=(nil)
printAddr (nil)
printAddr (nil)
// 2. dereference a nullptr pointer and pass it as reference
Dereferencing a null pointer is Undefined Behaviour, and so whether you pass it as a reference or by value, the fact is that you've dereferenced it and therefore invoked UB, meaning from that point on all bets are off.
You've already invoked UB here:
int &ir = *ip; //ip is null, you cannot deref it without invoking UB.