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;
}
It will work and has defined behavior since C++20. Doing it with a
constmember variable isn't allowed in prior versions.thisis such a pointer.Weirdis transparently replaceable byWeird.