I was reading a post on some nullptr
peculiarities in C++, and a particular example caused some confusion in my understanding.
Consider (simplified example from the aforementioned post):
struct A {
void non_static_mem_fn() {}
static void static_mem_fn() {}
};
A* p{nullptr};
/*1*/ *p;
/*6*/ p->non_static_mem_fn();
/*7*/ p->static_mem_fn();
According to the authors, expression /*1*/
that dereferences the nullptr
does not cause undefined behaviour by itself. Same with expression /*7*/
that uses the nullptr
-object to call a static function.
The justification is based on issue 315 in C++ Standard Core Language Closed Issues, Revision 100 that has
...
*p
is not an error whenp
is null unless the lvalue is converted to an rvalue (7.1 [conv.lval]), which it isn't here.
thus making a distinction between /*6*/
and /*7*/
.
So, the actual dereferencing of the nullptr
is not undefined behaviour (answer on SO, discussion under issue 232 of C++ Standard, ...). Thus, the validity of /*1*/
is understandable under this assumption.
However, how is /*7*/
guaranteed to not cause UB? As per the cited quote, there is no conversion of lvalue to rvalue in p->static_mem_fn();
. But the same is true for /*6*/
p->non_static_mem_fn();
, and I think my guess is confirmed by the quote from the same issue 315 regarding:
/*6*/
is explicitly noted as undefined in 12.2.2 [class.mfct.non-static], even though one could argue that sincenon_static_mem_fn();
is empty, there is no lvalue->rvalue conversion.
(in the quote, I changed "which" and f()
to get the connection to the notation used in this question).
So, why is such a distinction made for p->static_mem_fn();
and p->non_static_mem_fn();
regarding the causality of UB? Is there an intended use of calling static functions from pointers that could potentially be nullptr
?
Appendix:
- this question asks about why dereferencing a
nullptr
is undefined behaviour. While I agree that in most cases it is a bad idea, I do not believe the statement is absolutely correct as per the links and quotes here. - similar discussion in this Q/A with some links to issue 232.
- I was not able to find a question devoted to static methods and the
nullptr
dereferencing issue. Maybe I missed some obvious answer.