| |
| Posted by Adam D Ruppe in reply to Johann Lermer | PermalinkReply |
|
Adam D Ruppe
Posted in reply to Johann Lermer
| On Wednesday, 25 August 2021 at 12:11:01 UTC, Johann Lermer wrote:
> I have a little problem understanding alias this. I always thought, that alias this only makes implicit conversions from the aliased object to this.
What it does is if "a SOMETHING b" doesn't compile, it instead tries "a.alias_this_member SOMETHING b" instead, or "a SOMETHING b.alias_this_member" instead if that's on the other side. The object with alias this must already exist though, so constructors are an exception (though another object's constructor can trigger some existing object's alias this when used as a param to that).
The "SOMETHING" there can be operators like + or = or a .member.
Only if both fail to compile do you actually get an error.
> 17 Test_Struct ts = ac; // compiles
So what really happens here is the compiler sees ts = ac; fails to compile, so it is rewritten into "ts = ac.ts;"
> 18 ac = ts; // compiles as well - why?
So ac = ts fails, meaning it rewrites into `ac.ts = ts;`
> 20 auto tc = new Test_Class;
> 21 ts = tc.ac; // compiles
So here it is rewritten into `ts = tc.ac.ts`.
> 22 tc.ac = ts; // again this compiles, but seg faults
And now
tc.ac.ts = ts;
is the rewrite since the plain one didn't compile, thus accessing the null member.
Note too that alias this can be to a function, in which case the rewrite will call the function.
Implicit conversion isn't really what alias this is about. It kinda works (though note with a alias this struct it can be passed by value and thus copy, again the compiler just does the rewrite). It is just giving transparent access to a member.
|