Unifying ctor+Clear() inits into in-class initializers?

Hi,

https://reviews.llvm.org/D40212

At least DWARFCompileUnit and I see even for example MachVMRegion duplicate
intialization of fields in both their constructor and Clear(). Moreover the
initialization is in different place than declaration of the member variable.

Is it OK to just use in-class member variable initializers and:
  void Clear() {
    this->~ClassName();
    new (this) ClassName();
  }
?

Pavel Labath otherwise suggests to just call Clear() from the constructor.
Still then I find the code could be more readable with in-class members
initializers - moreover during further refactorizations+extensions.

Thanks,
Jan Kratochvil

⚙ D40212 DWZ 02/12: refactor: Unify+simplify DWARFCompileUnit ctor+Clear() into in-class initializers + Extract()

...

Is it OK to just use in-class member variable initializers and:
  void Clear() {
    this->~ClassName();
    new (this) ClassName();
  }
?

FYI Greg Clayton in the review above decided this is not good and it will be
better to avoid Clear() completely.

Jan Kratochvil

void Clear() {
this->~ClassName();
new (this) ClassName();
}

My 2c: this is clever, but not without downsides:

  1. It may do more than intended (it will destroy all members / bases)
  2. It forces construction and ‘reset’ to be exactly the same, which is not always desirable
  3. Most importantly if you really want a freshly initialized object, just do that (create a new object)

I like in-class initializers, but for clear/reset operations I prefer a standalone operation. And as Pavel suggested, calling ‘clear’ from the constructor is a good way to factor out commonality.

+1, this pattern looks like asking for UB