Is the following code safe? (I already know it compiles properly.)
void Tile::clear()
{
*this = Tile();
}
int main()
{
Tile mytile;
mytile.clear();
}
Is the following code safe? (I already know it compiles properly.)
void Tile::clear()
{
*this = Tile();
}
int main()
{
Tile mytile;
mytile.clear();
}
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.
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.
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.