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 20:18:09 +0200
On 22/06/2024 15.32, Yongwei Wu wrote:
> On Sat, 22 Jun 2024 at 15:41, Jens Maurer <jens.maurer_at_[hidden]> wrote:
>>> https://cplusplus.github.io/CWG/issues/2823.html
>>>
>>> According to this issue, ptr->h() is undefined.
>>
>> That's the result, yes.
>
> Consider this variant:
>
> class Obj {
> public:
> constexpr int f() { return d_; }
> constexpr int g() { return 0; }
> constexpr static int h() { return 1; }
>
> private:
> int d_{};
> };
>
> constexpr auto ptr = static_cast<Obj*>(nullptr);
> constexpr int n1 = ptr->f();
> constexpr int n2 = ptr->g();
> constexpr int n3 = ptr->h();
>
> Will the standard require all the last three lines to generate errors,
> as required by [expr.const]/5.8?
> https://eel.is/c++draft/expr.const#5.8

Yes.

> It seems to me a burden to the compilers, though I have no idea how
> difficult it is to implement it.

Compilers need to track values for constant evaluation.
Having a consistent check for nullptr at the time *p is
evaluated seems pretty simple.

> Currently, only the n1 line generates errors in the three main
> compilers I tested. The n3 line does not even trigger a warning.
>
> Due to the requirement that undefined behavior should mostly not occur
> in constant expressions, they have a cost to compilers.

The case n1 already needs to be diagnosed; n2 and n3 don't seem
to be much different.

Jens

Received on 2024-06-22 18:18:27