C++ Logo

SG12

Advanced search

Subject: Re: [ub] type punning through congruent base class?
From: Gabriel Dos Reis (gdr_at_[hidden])
Date: 2014-01-06 13:33:11


| -----Original Message-----
| From: ub-bounces_at_[hidden] [mailto:ub-bounces_at_[hidden]] On Behalf Of
| Fabio Fracassi
| Sent: Monday, January 6, 2014 7:35 AM
| To: 'WG21 UB study group'
| Subject: Re: [ub] type punning through congruent base class?
|
| > From: ub-bounces_at_[hidden] [mailto:ub-bounces_at_[hidden]] On
| > Behalf Of Gabriel Dos Reis
| > Sent: Montag, 6. Januar 2014 15:33
| >
| > "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?
| >
|
| It would enable us to extend or change the interface of a class without
| copying or moving the underlying object (think mixin without additional data).
| Of course we could make our "extention members" (like foo() in the example above)
| free functions which take a B&, but the grouping and the access to protected
| members would simplify the design.
|
| But use case for this example aside (for now), I'd still be curious if we were to
| allow this, would it interfere with aliasing?
|
| best regards
|
| Fabio

If Jason's workaround is insufficient for your needs, then I believe you are looking for fundamentally altering the C++ object model. That is a language design and largely philosophical issue ("what is the computing model of the language?"), well beyond "undefined behavior". At a personal level, I wouldn't take a design (like this) just because I know how to solve it technically.

-- Gaby


SG12 list run by herb.sutter at gmail.com