C++ Logo


Advanced search

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

From: Chris Jefferson <chris_at_[hidden]>
Date: Wed, 24 Jul 2013 23:04:06 +0100
On 24/07/13 22:29, Howard Hinnant wrote:
> Absolutely makes sense. And if we had a clean slate to work with, that's exactly what I would recommend.
> I'm currently looking at a benefit / cost decision, and from where I sit, the benefit looks large and the cost tiny:
> The benefit: We can make the copy assignment operator of map must faster for common cases. We're talking 2X, 3X, I've seen some cases go better than that. And there are some cases that don't go as well. There are no cases that are penalized.
> The cost: Require that compilers do not exploit what today is labeled undefined behavior in the union V. Currently no compilers do, to the best of my knowledge. There is no change in existing compiler behavior that is required. What is required is that standards writers work out the language to ensure this constraint on future compiler optimization development.
> If we were to present this data, the benefit, and the cost, to C++ programmers, and held a vote among that entire population, do you think C++ programmers would be in favor or against this engineering tradeoff?
> Do you think C++ programmers might be facing their own dilemmas that have striking similarity to ours with std::map? I know we are. Exact same issue with unordered_[multi]map.

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.


Received on 2013-07-25 00:04:25