Search code examples
c++undefined-behaviorplacement-new

Constructing an object over itself


In C++ can you reuse the memory of an object by destroying this and then recreating another object of the same type at this? Would it work or would it be UB?

In the following example we seemingly modify a const member variable (live demo).

#include <new>


class Weird {
public:
    Weird(int x) : x(x) {}

    void operator=(int newX) {
        this->~Weird();
        new(this) Weird(newX);
    }

    operator int() const {
        return x;
    }

private:
    const int x;
};


int main() {
    Weird w = 1;
    w = 2;
    return w;
}

Solution

  • Would it work or would it be UB?

    It will work and has defined behavior since C++20. Doing it with a const member variable isn't allowed in prior versions.

    after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that represents the address of the storage location where the object will be or was located may be used but only in limited ways.

    C++20 standard [basic.life/6]

    this is such a pointer.

    If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if the original object is transparently replaceable by the new object.

    C++20 standard [basic.life/8]

    Weird is transparently replaceable by Weird.