Truncheon
Truncheon

Reputation: 976

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();
}

Upvotes: 5

Views: 1401

Answers (4)

Potatoswatter
Potatoswatter

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

Madhava Gaikwad
Madhava Gaikwad

Reputation: 41

Safe if your copy consturctor is not doing anything nasty.

Upvotes: -1

Charles Salvia
Charles Salvia

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

sharptooth
sharptooth

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

Related Questions