C++ Logo

sg12

Advanced search

Re: [ub] type punning through congruent base class?

From: Gabriel Dos Reis <gdr_at_[hidden]>
Date: Mon, 06 Jan 2014 06:33:23 -0800
"Fabio Fracassi" <f.fracassi_at_[hidden]> writes:

| Hello UB-Experts,
|
| as far as I can see the following (static_cast) is UB:
|
| struct B {
| int i;
| };
|
| struct D : B {
| void foo() { /* access B::i */ }
| };
|
| B b;
| static_cast<D&>(b).foo();
|
| because of [expr.static.cast] clause 11
|
| first question: is my assessment of the situation correct or is this
| use legal?
| if it is not (legal): could we make it legal or would we run afoul of
| the aliasing rules?

Yes, it is undefined behavior -- you're referring to an inexistent
(sub)object of type D.

Why can't you create an object of type D if your program needs it? Why
is it a hardship?

-- Gaby

Received on 2014-01-06 15:40:02