views:

95

answers:

4

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

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

int main()
{
    Tile mytile;

    mytile.clear();
}
A: 

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.

sharptooth
How is this specific to the question? If a constructor doesn't properly initialize a member, doing _anything_ with the object might invoke undefined behavior.
sbi
@sbi: Not anything. You could have an unused uninitialized pointer member variable. In this case you can safely instantiate and destroy the object. My point is that *it depends*.
sharptooth
@sharptooth: Sorry, but that doesn't fly. Such a beast could also be assigned to and from.
sbi
@sbi: Yes, but UB will not be invoked until the assignment is invoked. If you for example create a temporary object and pass it by reference no UB happens. Again, my point is not that *it is good* or *it is bad*. My point is *it depends, show me the code*.
sharptooth
+10  A: 

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.

Charles Salvia
A: 

Safe if your copy consturctor is not doing anything nasty.

Madhava Gaikwad
copy constructor is not invoked in given code.
YeenFei
+1  A: 

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.

Potatoswatter
Then that's one thing where I disagree with Herb. Construction, even copy construction, and assignment are two different operations for a reason. If anything, the assignment operator should use the [copy-and-swap idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom), that is: it _does_ use the copy constructor, albeit in a better way than the one Herb's article started out with.
sbi