In the comments to this answer, Koushik raised a very valid point.
Take the following:
union U
{
int x;
const T y;
};
(I choose T
such that there is no common initial sequence of layout compatibility here, meaning only one member may be active at any given time per [C++11: 9.5/1]
.)
Since only one member may be "active" at any one time (made active by writing to it), and y
cannot be written to after initialisation, isn't this rather pointless? I mean, y
can only be read from until the first time x
is written to, and at that only if y
was the initialised member.
Is there some use case I'm missing? Or is this indeed a pretty pointless confluence of language features?
It does have uses:
1) For offering a
const_cast
-like technique. In a sense,x = const_cast<...>(y)
.2) When dealing with templates, sometimes you need a
const
version of a data type so you match other parameter types.(I've seen (1) used when programming against legacy interfaces).
If the union represents part of a result of some method/algorithm, then it could make sense. But in that case, I'd make both values
const
:Here's a contrived example of a reference-semantics type where you'd only want to grant
const
access to. Theunion
is used in a variant-like data type returned from a "type-erasing" function.Imagine now that instead of
int
anddouble
, much larger data types are used, and that thereference_semantics
data type actually provides more functionality than just returning the value.It might even be possible that you want to return a
reference_semantics<some_type> const
for some arguments, but a plainint
for others. In that case, yourunion
might even have const and non-const members.Not using unions a lot, but this might be scenario:
Note: From 9.5 Unions