C++ Logo

sg12

Advanced search

Re: [ub] [c++std-core-23844] Re: unions and undefined behavior

From: Marc Glisse <marc.glisse_at_[hidden]>
Date: Sat, 27 Jul 2013 12:09:17 +0200 (CEST)
On Wed, 24 Jul 2013, Chris Jefferson wrote:

> A similar dilemma I hit recently.
>
> I know (on all platforms I care about) that I never form a pointer to
> address '1'.
>
> Here is a trick to implement std::optional<T> for most standard
> containers T, with no memory overhead. If I know where a pointer exists
> in an object of type T, write (void*)1 into that memory location to
> represent 'I have no constructed a T, the optional is disengaged'. If I
> read that memory location and find something other than (void*)1, I know
> there is a constructed T in the memory.
>
> After a bit of thought, I decided I simply didn't understand the rules
> well enough on how to do this legally (or if there was any legal way of
> implementing it), so gave up.

Casting 1 to void* is legal. The resulting value is implementation defined
(the only requirement is that ptr -> large enough int -> ptr is the
identity). Now here comes the bit where you say your implementations
document that (void*)1 cannot be a valid pointer (do they?). Then it looks
fine to me without any fancy workaround. That's because it casts a value,
it doesn't cast a pointer to it (which might also be doable, but harder).

Note that I just heard (haven't checked) that recent Solaris return
(void*)1 for realloc(ptr,0). It looks questionable, but I wonder if that
may interfere with your technique.

-- 
Marc Glisse

Received on 2013-07-27 12:09:37