logical const idea - scratchspace

H. S. Teoh hsteoh at quickfur.ath.cx
Mon May 14 13:12:33 PDT 2012


On Mon, May 14, 2012 at 03:51:09PM -0400, Steven Schveighoffer wrote:
> I have an idea on how to create logical const without any language
> or compiler changes -- it will exist purely in druntime.
[...]
> In essence, a const(MyObj) is a pointer to a struct that looks like:
> 
> struct FicticiousMyObjStruct
> {
>   const(MyObj_data); // not a reference, the actual data
>   ubyte[8] scratchspace;
> }
> 
> So we need two pieces for this proposal:
> 
> 1. An accessor in Object for this scratch space.  This should be a)
> efficient, and b) opaque.
> 2. An allocator for a new object that can allocate a minimal scratch
> space.  So for instance, if your object consumes 32 bytes, but you
> need 20 bytes of scratch space, you want the runtime to allocate a
> 64 byte block.  So instead of saying new MyObject, you'd say
> newScratchSpace!MyObject(20)
> 
> And I think that's it.  Since nothing before this proposal ever
> referred to or used that scratch space, it's not in danger of
> breaking existing code.  The only caveat is, it can't properly be
> typed as shared or not (it could be accessible from multiple
> threads, depending on if the actual type is immutable).
[...]

This is all cool and everything, but I'm having a bit of trouble
imagining how this helps us to implement logical const. Is the idea
merely for every object to come with some sort of extra untyped
non-const space that can be used for memoization, storing temporary
state, etc.? How is this different from introducing a 'mutable' keyword
to the language, or some other such change? (A mutable member of a const
object is essentially the same as a member stored in this 'scratch
space' of yours.)

This still doesn't help establish logical constness, since nothing stops
you from creating a class with all data inside the scratch space, in
which case const/immutable no longer has any meaning. Then we will have
devolved back to the land of C++'s const, where calling an immutable
method can freely modify arbitrary data (except that instead of a cast
we use scratchspace).


T

-- 
Just because you survived after you did it, doesn't mean it wasn't stupid!


More information about the Digitalmars-d mailing list