C++ Logo

std-discussion

Advanced search

Re: Indirection of nullptr that is not really done

From: Jens Maurer <jens.maurer_at_[hidden]>
Date: Sat, 22 Jun 2024 09:41:28 +0200
On 22/06/2024 08.14, Yongwei Wu via Std-Discussion wrote:
> I saw some discussions about whether some code is undefined behavior. Example:
>
> class Obj {
> public:
> int f() { return d_; }
> void g() {}
> static void h() {}
>
> private:
> int d_;
> };
>
> auto ptr = static_cast<Obj*>(nullptr);
> ptr->f(); // Clearly undefined
> ptr->g(); // Arguably undefined
> ptr->h(); // ?

All three are undefined behavior, because ptr->something is rewritten
as (*ptr).something, and the null pointer dereference is undefined
behavior per [expr.unary.op] p1. There is no such thing as a null
lvalue or null reference. (Some people are unhappy with that outcome,
but CWG feels a paper to EWG with analysis and rationale is needed to
change the situation.)

> In the last two cases, nullptr is never dereferenced, especially the
> ptr->h() case, where the object pointer is not used at all. Is the
> last case really undefined?
>
> https://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#315
>
> According to this issue, ptr->h() is OK.

That issue is more than 20 years old.
Meanwhile, the direction of CWG has changed towards a uniform
treatment of null pointer values, embodied in the following issue.
I've amended CWG315 with a cross-reference:

https://cplusplus.github.io/CWG/issues/315.html

> https://cplusplus.github.io/CWG/issues/2823.html
>
> According to this issue, ptr->h() is undefined.

That's the result, yes.

> Should we mention lvalue-to-rvalue conversion in expr.unary.op/1?

Why?

Jens

Received on 2024-06-22 07:41:34