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.