Reputation: 976
Is the following code safe? (I already know it compiles properly.)
void Tile::clear()
{
*this = Tile();
}
int main()
{
Tile mytile;
mytile.clear();
}
Upvotes: 5
Views: 1401
Reputation: 137860
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.
Upvotes: 1
Reputation: 53319
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.
Upvotes: 10
Reputation: 170509
It depends on implementation. For example if the assignment operator relies on some member variable of class Tile
being already initialized (and that is quite usual) and that variable is not initialized by the Tile
constructor before you call the *this =
assignment you program might run into undefined behavior.
Upvotes: 0