Are D classes proper reference types?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Fri Jun 25 06:09:17 UTC 2021


On Thursday, 24 June 2021 at 07:28:56 UTC, kinke wrote:
> Yes, class *refs* are always pointers. *scope* classes are 
> deprecated (I don't think I've ever seen one); with `scope c = 
> new Object`, you can have the compiler allocate a class 
> *instance* on the stack for you, but `c` is still a *ref*.

But the user code cannot depend on it being stack allocated? So I 
could replace the Object reference with a reference counting 
pointer and put the counter at a negative offset?

> `emplace` doesn't allocate, you have to pass the memory 
> explicitly.

This is more of a problem. I was thinking about arrays that 
provide an emplace method, then one could replace emplace with 
heap allocation. I guess it isn't really possible to make 
`emplace` with custom memory work gracefully with reference 
counting with ref count at negative offset.

> A class *instance* can also live in the static data segment 
> (`static immutable myStaticObject = new Object;`);

But it isn't required to? It certainly wouldn't work with 
reference counting if it is stored in read only memory...

> `extern(C++)` class instances can also live on the C++ 
> heap/stack etc. etc.

Yes, that cannot be avoided.



More information about the Digitalmars-d-learn mailing list