C++ Logo

std-discussion

Advanced search

Re: Does destruction clobber storage?

From: (wrong string) Åberg <haberg_1_at_[hidden]>
Date: Fri, 11 Jul 2025 09:38:57 +0200
The standard just says that the moved-from object should be left in a valid but otherwise unspecified state, and there are different ways to implement this. One is using a swap, but the destruction order gets out of sync, and it may not be as fast as first destroying the moved-to object, move, and then set a suitable value to the moved-from object, such as nullptr in the case of pointers. It looks, in the case of std::unique_ptr, as though GCC is using the swap method and Clang the destroy and move method.


> On 10 Jul 2025, at 23:56, Ell via Std-Discussion <std-discussion_at_[hidden]> wrote:
>
> If an array provides storage for an object, does destroying the object
> "invalidate" the contents of the array?
>
> void f () {
> unsigned char a[1];
>
> using T = unsigned char;
>
> T* p = new (a) T (123);
> unsigned char x = a[0];
> p->~T ();
>
> unsigned char y = a[0];
>
> assert (x == y);
> }
>
> The assert passes using clang (and msvc), but not gcc with optimizations
> on. Is gcc doing the "right thing" here? Is this UB? EB?
>
> I'm mostly asking because of how this affects types like vector:
>
> auto f (std::vector<std::unique_ptr<int>>& v) {
> auto x = std::move (v.back ());
>
> v.pop_back ();
>
> return x;
> }
>
> Here clang bothers to zero out the moved-from unique_ptr, even though it
> knows the subsequent destructor is a nop, while gcc doesn't [1].
> Obviously (?), gcc's behavior is preferable, but is it correct?
>
> [1] https://godbolt.org/z/b663K1bnd

Received on 2025-07-11 07:39:14