|Union C++ standard DrDiettrich1@netscape.net (Hans-Peter Diettrich) (2021-11-25)|
|Re: Union C++ standard firstname.lastname@example.org (Kaz Kylheku) (2021-11-26)|
|Re: Union C++ standard email@example.com (gah4) (2021-11-26)|
|Re: Union C++ standard firstname.lastname@example.org (David Brown) (2021-11-27)|
|Re: Union C++ standard derek@NOSPAM-knosof.co.uk (Derek Jones) (2021-11-28)|
|Re: Union C++ standard email@example.com (David Brown) (2021-11-28)|
|Re: Union C++ standard derek@NOSPAM-knosof.co.uk (Derek Jones) (2021-11-29)|
|Re: Union C++ standard firstname.lastname@example.org (Kaz Kylheku) (2021-11-29)|
|Re: Union C++ standard email@example.com (David Brown) (2021-11-29)|
|Re: Union C++ standard Keith.S.Thompsonfirstname.lastname@example.org (Keith Thompson) (2021-11-29)|
|[4 later articles]|
|From:||David Brown <email@example.com>|
|Date:||Sat, 27 Nov 2021 16:59:36 +0100|
|Organization:||A noiseless patient Spider|
|Injection-Info:||gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="50781"; mail-complaints-to="firstname.lastname@example.org"|
|Posted-Date:||27 Nov 2021 14:29:18 EST|
On 25/11/2021 11:11, Hans-Peter Diettrich wrote:
> Can somebody explain why the access to members of a union is "undefined"
> except for the most recently written member?
> What can be undefined in a union of data types of the same typesize end
> alignment? Any member written will result in a unique bit/byte pattern
> in memory, whose reading may not make sense in a different type but
> undoubtedly is well defined.
> [I think it's undefined in a standards sense. In any individual
> implementation the result is predictable, but it's not portable. -John]
In C++, objects of a class typically have some kind of invariant which
is established by the constructor, and kept consistent when accessed via
its public methods. Messing with the underlying data representation
directly is going to risk losing that - it means you are accessing data
without going through the proper defined interface (the public or
protected methods and members).
In C, type-punning via unions is allowed (i.e., fully defined behaviour
in the standards), but not in C++ where the language is expected to
enforce higher-level aspects of the data.
Return to the
Search the comp.compilers archives again.