Home > database >  Can I safely move assign to `this`?
Can I safely move assign to `this`?

Time:06-11

I was wondering if it's safe to write a reset method of some class A by using the move assignment operator on this.

So instead of

A a{};
... // Do something with a
a = A();

if I could write

A a{};
... // Do something with a
a.reset();

where

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

I played arround a bit on godbolt (https://godbolt.org/z/Edc3TT1aT ) and the resulting debug assembly is almost identical with gdb for this example.

CodePudding user response:

In general, assigning to *this is not wrong. Neither copy nor move.

Whether it's correct depends on what your move assignment operator does, and what you need the reset function to do. If the assignment does the right thing, then it's correct.

  • Related