C++ Logo

std-discussion

Advanced search

Does destruction clobber storage?

From: Ell <ell_se_at_[hidden]>
Date: Fri, 11 Jul 2025 00:56:44 +0300
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-10 21:56:58