www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - How immutable is an object's vptr?

reply Johan Engelen <j j.nl> writes:
Hi all,
   I'm working on (basic) devirtualization, and am wondering how 
immutable the vptr is in D. There is no clear spec on this.
I am currently assuming that an object's vptr is completely 
immutable and that use of the object after changes to its vptr 
are UB (in contrast to the more complicated situation in C++).

Please help me find an example where this assumption does not 
hold.

```
class A {
   void foo();
}

void may_do_anything(A a); // e.g. delete, destroy, ...

void my_current_assumption(A a) {
   a.foo();
   auto tempvptr = a.__vptr;
   // The assumption is that if the vptr changes, that use of `a` 
afterwards is UB.
   may_do_anything(a);
   a.foo(); // either UB or identical to "tempvptr.foo(a)" (pardon 
the notation)
}

void test_vptr(A a) {
   a.foo();
   may_do_anything(a);
   if (a.__vptr) { // use of `a`, so the check is UB if vptr has 
changed
      //...
   }
}
```

-Johan
Nov 11 2017
parent Guillaume Piolat <contact spam.com> writes:
On Saturday, 11 November 2017 at 12:52:09 UTC, Johan Engelen 
wrote:
 Hi all,
   I'm working on (basic) devirtualization, and am wondering how 
 immutable the vptr is in D. There is no clear spec on this.
 I am currently assuming that an object's vptr is completely 
 immutable and that use of the object after changes to its vptr 
 are UB (in contrast to the more complicated situation in C++).

 Please help me find an example where this assumption does not 
 hold.

 ```
 class A {
   void foo();
 }
IIRC entry 0 of the vtable is for TypeInfo*, so at least casting and destruction won't work correctly.
Nov 11 2017