www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - std::make_shared and ARC

I've been thinking a bit about how one could add reference 
counting, ARC and staying compatible with C++.

First we assume that C++ make_shared allocates the shared_ptr 
node at a fixed offset in front of the class being instantiated. 
So a D implementation could take advantage of this and avoid the 
reference counting mechanism as long as the compiler can 
statically establish that the reference ownership is isolated.

What is basically needed is a class pointer type that ensures 
that the pointed to shared_ptr node is at a fixed offset from the 
actual instance.

If all D class objects were instantiated with a shared_ptr node 
at a fixed offset by default (unless explicitly made not to) then 
these objects could later be shared with C++ and D could still 
retain the performance boost from avoiding the indirection.

Likewise external C++ functions that return std::shared_ptr could 
have their signature annotated to indicate to the D compiler that 
specific shared_ptr actually is at a fixed offset from the 
pointed to object.

Furthermore if the D compiler can prove that an object is never 
shared it could optimize out the shared_ptr node. Which would be 
a tad bit more transparent (in terms of type erasure) if the 
shared_ptr node is at a negative offset, then there would be no 
difference in representation between a shared_ptr with a fixed 
offset and a regular pointer.
Oct 22 2020