5

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

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

int main()
{
    Tile mytile;

    mytile.clear();
}
Truncheon
  • 916
  • 2
  • 12
  • 25

4 Answers4

10

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
  • 52,325
  • 13
  • 128
  • 140
1

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
  • 134,909
  • 25
  • 265
  • 421
  • 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 Oct 08 '10 at 07:02
0

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
  • 167,383
  • 100
  • 513
  • 979
  • 1
    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 Oct 08 '10 at 06:57
  • @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 Oct 08 '10 at 07:06
  • Sorry, but that doesn't fly. Such a beast could also be assigned to and from. – sbi Oct 08 '10 at 07:50
  • @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 Oct 08 '10 at 07:54
-1

Safe if your copy consturctor is not doing anything nasty.