C++ Logo

std-proposals

Advanced search

Re: [std-proposals] void std::optional<T>::abandon(void) noexcept

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Wed, 29 Nov 2023 15:29:20 +0000
On Wed, 2023-11-29 at 15:11 +0000, Frederick Virchanza Gotham via Std-
Proposals wrote:
> On Wed, Nov 29, 2023 Lénárd Szolnoki via Std-Proposals wrote:
> >
> > The precondition for memcpy is trivially copyable *and* not
> > potentially
> > overlapping. The former doesn't imply the latter.
> >
> > https://godbolt.org/z/xhsqdoz3s
>
>
> I've been playing around with this on GodBolt:
>
> https://godbolt.org/z/Ecd338Go8
>
> The output of this program on Linux x86_64 GNU g++ 13.2.0 is:
>
> Address of b.a.i == 140727507144480
> Address of b.a.ch == 140727507144484
> Address of b.maybe_extra_byte == 140727507144485
> 77
> 0
>
> So I am able to screw up the value of 'maybe_extra_byte' by
> memcpy'ing
> over the A object that exists inside B. Is this what the committee
> intended?

Yes. Potentially overlapping subobjects are inherently incompatible
with memcpy. This is somewhat explicitly undefined behavior, as
potentially-overlapping subobjects are excluded from the specification
of memcpy:

https://eel.is/c++draft/basic#types.general-2
https://eel.is/c++draft/basic#types.general-3


> If this _is_ what the compiler intended, then should every C++
> compiler issue a diagnostic whenever you pass the address of a
> 'no_unique_address' object to memcpy?

'no_unique_address' members and base subobjects are equally affected.

You are right that a warning might be warranted, but in general it's
not always possible to protect against this. In general it's not
possible to decide whether an arbitrary pointer value or reference
refer to a potentially overlapping subobject. So even if the warning
could be triggered in simple cases, it's not clear whether the warning
could work in more complex cases, like in tuple or optional.

I don't see a path of making this ill-formed, unless it's somehow
incorporated into the type system.

Received on 2023-11-29 15:29:25