Constructing a class in-place

rikki cattermole rikki at cattermole.co.nz
Thu Jul 26 12:53:44 UTC 2018


On 27/07/2018 12:45 AM, Johan Engelen wrote:
> On Wednesday, 25 July 2018 at 08:11:59 UTC, rikki cattermole wrote:
>>
>> Standard solution[0].
>>
>> [0] https://dlang.org/phobos/std_conv.html#.emplace.4
> 
> Thanks for pointing to D's placement new. This is bad news for my 
> devirtualization work; before, I thought D is in a better situation than 
> C++, but now it seems we may be worse off.
> 
> Before I continue the work, I'll have to look closer at this (perhaps 
> write an article about the situation in D, so more ppl can help and see 
> what is going on). In short:
> C++'s placement new can change the dynamic type of an object, which is 
> problematic for devirtualization. However, in C++ the pointer passed to 
> placement new may not be used afterwards (it'd be UB). This means that 
> the code `A* a = new A(); a->foo(); a->foo();` is guaranteed to call the 
> same function `A::foo` twice, because if the first call to `foo` would 
> do a placement new on `a` (e.g. through `this`), the second call would 
> be UB.
> In D, we don't have placement new, great! And now, I learn that the 
> _standard library_ _does_ have something that looks like placement new, 
> but without extra guarantees of the spec that C++ has.
> For some more info:
> https://stackoverflow.com/a/49569305
> https://stackoverflow.com/a/48164192
> 
> - Johan

Both of those links is related to structs not classes (and original post 
is about classes).
Given the content (I could be wrong) but I don't think its related to 
our situation in D.

Classes in D are very "heavy" with their explicit vtable. Given that 
classes in C++ can act as a value and a reference type, you have to be 
pretty careful when comparing them.


More information about the Digitalmars-d mailing list