C++ Logo

sg12

Advanced search

Re: [ub] Is dereferencing this pointer a UB?

From: Jens Maurer <Jens.Maurer_at_[hidden]>
Date: Fri, 11 Aug 2017 13:47:25 +0200
On 08/11/2017 09:58 AM, Andrzej Krzemienski wrote:
> Hi SG12 Members,
>
> I already asked this question in ISO C++ Standard - Discussion (https://groups.google.com/a/isocpp.org/forum/?fromgroups=#!topic/std-discussion/UbROFU6Fs0E <https://groups.google.com/a/isocpp.org/forum/?fromgroups=#%21topic/std-discussion/UbROFU6Fs0E>), but maybe this list is better suited.
>
> UB-sanitizer reports a runtime error for the following program:
>
> ```
> struct B;
>
> struct I {
> virtual void f() {}; // <- virtual
> };
>
> struct A : I {
> A();
> };
>
> struct B : A {
> };
>
> A::A() { *static_cast<B*>(this); } // <- UB in static_cast
>
> int main()
> {
> B{};
> }
> ```
>
> My question: is UB-sanitizer correct? Is this a UB according to the standard? And if so, could you point me to the relevant sections?

The dereference here is immaterial; it just converts a pointer to an lvalue,
neither of which accesses the pointed-to value per se.

The conversion happens while A and B are being constructed, and we have
special rules in 15.7 [class.cdtor] for that. Of particular interest
is p2, which discusses conversions from B* to A*, but 8.2.9 [expr.static.cast]
indirectly refers to that case when discussing the A* to B* case.

Both the construction of B and A have started at the point in question,
so it seems to me the pointer conversion is, in fact, valid.

Jens

Received on 2017-08-11 13:52:39