Spec: can a class method change the type of the object (vtable) ?

Dukc ajieskola at gmail.com
Mon Mar 18 15:50:03 UTC 2024


On Sunday, 17 March 2024 at 12:47:49 UTC, Johan wrote:
> Although accepted by the compiler currently, I believe this is 
> forbidden by the spec (can't find it, if it is not in the spec 
> it should be added):
> ```
>     void foo() {
>         this = new B(); // illegal D code
>     }
> ```

This wouldn't accomplish anything if it was allowed. Remember, 
`foo` is
```D
void foo(A this) { this = new B; }
```
under the hood. You aren't modifying the existing instance of the 
class with this, you're only allocating a new instance and then 
not doing anything neither with the old nor the new instance.

I believe you meant
```D
     void foo() {
         import core.lifetime;
         this.destroy(false);
         emplace(cast(B) cast(void*) this);
     }
```


More information about the Digitalmars-d mailing list