Idea to ease tail-const class reference woes

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 21 06:48:35 PDT 2008


I thought of this idea to compromise a bit in the tail-const class reference 
debate.

Before I outline my idea, let me just say that my first preference is to be 
able to have true tail-const class references, or at least to have Walter 
commit to providing tail-const class references before D2.0 is finalized. 
But it's looking more and more like that isn't going to happen (not for any 
good reason I can see BTW).

So here goes...

We have tail-const value types without a problem in D, they look like:

const(int)* tailConstInt;

tailConstInt can be rebinded, but you cannot change what it points to.  It 
is easy to instantiate or assign a tail-const int:

int x = 5;
const(int)* cx = &x;

Or if you need a tail-const int that lives on the heap:

int *x = new int; // would be nice to be able to do new int(5)
*x = 5;
const(int)* cx = x;

If you need a tail-const class reference, you can do

C myClass = new C;
const(C)* constClass = &myClass;

Now, I can rebind constClass, but I cannot change the class through that 
reference.  However, once this function goes out of scope, if constClass is 
a global, I now have to keep the stack frame around.  If I want to allocate 
a class reference on the heap, there is no direct way to do it.  The easiest 
way to do it I know of is:

C myClass = new C;
const(C)[] tmp;
tmp ~= myClass;
const(C)* constClass = &tmp[0];

Which not only is a pain (and ugly), but I now have allocated an extra chunk 
of memory to hold a class reference.  I do not have to do this with an int, 
because the int is not inherently a reference, and I don't need two levels 
of indirection.

So my idea is to include in the class data a const reference to itself. 
Then provide a way to access that const reference.  In this way, tail-const 
classes become easy:

C myClass = new C;
const(C)* constClass = &myClass.constref;

Now, no extra heap allocation, and it is easy to specify a tail-const class 
reference.  Of course, there is still the issue of double-dereferencing to 
use the class, but that's an O(1) operation, and so shouldn't matter too 
much.  True tail-const class references would be preferrable for this 
reason, but this is a compromise.

Some would argue that doing this adds extra heap data, but in reality, 
allocations happen at the smallest in 16 or 32 byte chunks.  Chances are 
high that your class heap block still has 4 bytes (or 8 for 64-bit archs) 
left to put the extra pointer in.  Only in specific cases would this become 
a burden.

Does this sound reasonable?

-Steve 





More information about the Digitalmars-d mailing list