When making a curses version of Snake, I found that the this
pointer was bindable for reconstruction from inside an 'update' method.
The issue with this is that, although very convenient (saves having to rebind 'player' in a game object), it doesn't feel particularly idiomatic.
Using the snake as an example, we'd be destroying it and reconstructing it as we're inside a method call on the initial(?) snake.
Here's an example of rebinding this
in some struct A
:
struct A
{
int first;
A(int first) : first(first){};
void method(int i);
};
void A::method(int i)
{
*this = i;
}
This article explores the influence of idiomatic syntactic constructions (i.e., constructions whose phrase structure rules violate the rules that underlie the construction of other kinds of sentences in the language) on the acquisition of phrase structure.
The word “idiom” comes from the Greek word “idioma,” meaning peculiar phrasing. For example, “under the weather” is an idiom universally understood to mean sick or ill. If you say you're feeling “under the weather,” you don't literally mean that you're standing underneath the rain.
Definition of an idiomatic expression:an expression whose meanings cannot be inferred from the meanings of the words that comprise it.
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);
*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.
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