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 13:30:56 +0000
On Wed, 2023-11-29 at 12:53 +0000, Jonathan Wakely via Std-Proposals
wrote:
>
>
> On Wed, 29 Nov 2023 at 12:41, Andrey Semashev via Std-Proposals
> <std-proposals_at_[hidden]> wrote:
> > On 11/29/23 15:18, Jonathan Wakely via Std-Proposals wrote:
> > >
> > >
> > > On Wed, 29 Nov 2023 at 11:13, Giuseppe D'Angelo via Std-Proposals
> > > <std-proposals_at_[hidden]
> > > <mailto:std-proposals_at_[hidden]>>
> > > wrote:
> > >
> > > Il 29/11/23 11:46, Breno Guimarães via Std-Proposals ha
> > > scritto:
> > > > I don't think that's UB. Not calling the destructor is not
> > > UB.
> > >
> > > I was referring to the memset. But indeed I can't seem to
> > > find a
> > > provision that you can't just overwrite bytes of an
> > > arbitrary object
> > > using it. Interesting pub quiz question...
> > >
> > >
> > > There's no guarantee that the bytes of std::future<bool> are
> > > contiguous,
> > > so memset could overwrite something that's not part of the
> > > object.
> > >
> > > And clearly zeroing out the bytes of a std::vector and then
> > > expecting it
> > > to keep working afterwards isn't reasonable. I think fiddling
> > > with the
> > > underlying bytes is only valid for trivially copyable types.
> >
> > Not even then, I think. It is permitted for std::optional<T> to
> > store
> > the "populated" flag in the tail padding of the stored object (e.g.
> > by
> > creating an object of a class that derives from T), which means
> > that the
> > memset would corrupt that flag.
> >
>
>
> I don't think compilers will reuse tail padding of trivially-copyable
> types, precisely because using memcpy to change the value of a
> trivially copyable type is allowed.

The precondition for memcpy is trivially copyable *and* not potentially
overlapping. The former doesn't imply the latter.

https://godbolt.org/z/xhsqdoz3s

Unless standard containers/other types don't guarantee that contained
objects are not potentially overlapping then users can't rely on it.
For example `tuple` doesn't guarantee it, so `memcpy` over a member of
it is UB. Only empty members are potentially overlapping though in
common implementations, AFAIK. I don't think that `optional` guarantees
non-potentially overlapping either, but potentially overlapping
optional member is probably unimplementable without
[[no_unique_address]].

>
> In any case, using memset can produce an invalid object even on
> trivially-copyable types. The object representation created by memset
> might not be a valid value representation for the type. Only memcpy
> of bytes from a valid value representation of another object is
> guaranteed to work.
>
> But this is all a diversion from the fact that this abandon proposal
> is just a bad idea.
>

Received on 2023-11-29 13:31:02