Is it valid to call destructor on 'this' and then assign a new value to 'this'?

Viewed 146

Suppose I'm implementing some class A that has a clear() method that should set the object state to the "brand new" state as if it has just been created with a constructor:

  • I should free all the resources that the current object is using (exactly the same thing A::~A() does),
  • and then I should initialize those resources again (exactly the same thing A::A() does).

So my initial idea was as follows:

void A::clear() {
  this->~A();
  *this = A();
}

However, I was told that this code causes UB since I cannot dereference this after calling its destructor. But at the same time I was told a better idea as well: if we use placement new, there is no dereferencing, so this actually might work:

void A::clear() {
  this->~A();
  new (this) A();
}

This feels extremely uncomfortable and as error-prone as it gets... So is this code actually valid?

1 Answers

is this code actually valid?

Your code is valid. It's also a rather unusual approach to merely change the object's value.

The assignment operator alone, if implemented correctly, will achieve this.

void A::clear() {
  *this = A();
}

If this code does not work as expected, your assignment operator has been incorrectly implemented.

Related