alias this - am I using it wrong?
FeepingCreature
feepingcreature at gmail.com
Wed Aug 25 12:23:32 UTC 2021
On Wednesday, 25 August 2021 at 12:11:01 UTC, Johann Lermer wrote:
> Hi all,
>
> I have a little problem understanding alias this. I always
> thought, that alias this only makes implicit conversions from
> the aliased object to this. Then, why do lines 18 and 22
> compile in the code below? And, btw, line 22 crashes with a
> segmentation fault.
>
> ```d
> 01 struct Test_Struct {long t;}
> 02
> 03 class Alias_Class
> 04 {
> 05 Test_Struct ts;
> 06 alias ts this;
> 07 }
> 08
> 09 class Test_Class
> 10 {
> 11 Alias_Class ac;
> 12 }
> 13
> 14 void main ()
> 15 {
> 16 auto ac = new Alias_Class;
> 17 Test_Struct ts = ac; // compiles
> 18 ac = ts; // compiles as well - why?
> 19
> 20 auto tc = new Test_Class;
> 21 ts = tc.ac; // compiles
> 22 tc.ac = ts; // again this compiles, but seg
> faults
> 23 }
> ```
>
> Johann
ts is a field. You can assign to a field. So when the field is
aliased to this, you can assign to the field through a class
reference.
You can disable this behavior by creating a getter in
Alias_Class, then aliasing it to this:
```
class Alias_Class
{
Test_Struct ts;
Test_Struct getter() { return ts; }
alias getter this;
}
```
More information about the Digitalmars-d-learn
mailing list