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

So my questions are:


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.