以下是否会导致未定义的行为?
pointer2 的值应该为 NULL 吗?
double *pointer = 0;
double &value = *pointer;
double *pointer2 = &value;
最佳答案
是的。
double *pointer = 0; // init `pointer` to a NULL pointer value
double &value = *pointer; // dereference it
标准专门针对这种情况 - 来自 8.3.2/4“引用”:
A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]
关于C++标准题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3858470/