Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using *this in C++ class method to fully overwrite self instantiation

Is the following code safe? (I already know it compiles properly.)

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

int main()
{
    Tile mytile;

    mytile.clear();
}
like image 481
Truncheon Avatar asked Oct 08 '10 05:10

Truncheon


2 Answers

It might work. It depends on how Tile& operator = (const Tile&); is implemented. However, there's nothing intrinsically erroneous with assigning *this to a new value.

like image 127
Charles Salvia Avatar answered Oct 06 '22 00:10

Charles Salvia


The code is OK, and Herb Sutter even recommends calling the assignment operator on this, even within a constructor. I think that is an extremely clean, elegant solution. Even if it doesn't work at first, changing your code to make it work would probably be a matter of clean-up.

like image 29
Potatoswatter Avatar answered Oct 05 '22 23:10

Potatoswatter