Search code examples
c++constructorlanguage-lawyerc++17this-pointer

Is *this = Ctor(); legal and efficient for clearing an object's state?


I've stumbled across this piece of code to reestablish class invariants:

class Foo {
  // some stuff in here
public:
  void clear() {
    *this = Foo();
    //operator=(Foo()); // commented out in favor of the line above
  }
};
  • I would assume that the call to operator= is legal and works as expected, but will create an unnecessary temporary, in case the class is not movable. So it would probably be more efficient to manually assign default values, which is cumbersome and error-prone if we want to extend the class.
  • *this = Foo(), if allowed, is probably more efficient, as copy elision could work here I assume (regardless of the class being movable).

So my questions are:

  • Is the statement *this = Foo(); legal? If yes, please provide a reference to the standard
  • What is more efficient (providing that the first bullet point is true)?
  • In case Foo is movable.
  • In case it's not.

Solution

    • Is the statement *this = Foo(); legal? If yes, please provide a reference to the standard

    That's legal yes. It follows the standard that the value can be assigned through a dereferenced pointer.

    I don't think we can find anything in the c++-standard mentioning the situation, since it's not a special situation as you think it is.
    Assigning a dereferenced *this pointer works as with any other pointer.

    • What is more efficient (providing that the first bullet point is true)?
      • In case Foo is movable.
      • In case it's not.

    There are no differences regarding efficiency. Copy elision will be taken by any decent modern c++ compiler.