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
}
};
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:
*this = Foo();
legal? If yes, please provide a reference to the standardFoo
is movable.
- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With