Is it idiomatic to construct against `this`?

*this = i; implicitly constructs new instance of A as A::A(int) is not an explicit constructor and therefore creates the implicit conversion from int to A. *this = i; then calls default A::operator= with this new instance of A constructed from i. Then the new instance of A is destroyed.

So the code *this = i; is equivalent to operator=(A(i)); in your case.

It's legal to do so, but the code readability suffers from such a big amount of implicit actions.


You aren't destroying the object pointed to by this, you are calling it's operator=, which will copy first from a temporary initialised from i. You destroy the temporary after the assignment.

It might be clearer to write an A& operator=(int) which had the same effect.


It's legal, but if I saw it I would question whether the author knew what they were doing: Did they really mean to invoke this->operator=()? Surely there's a better way to do... whatever it is they're trying to do.

In your case, *this = i is equivalent to this->operator=(i). Since there's no operator=(int) defined, it uses the default assignment operator and the A(int) constructor to perform this->operator=(A(i)). The net effect is exactly the same as if you had written:

this->first = i;

Why didn't they just assign to first directly? I'd be asking.

If for some reason you do want all those steps, I'd at least make the implicit A(int) construction explicit:

*this = A(i);

Tags:

C++