Head Const

Iakh via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 19 12:46:24 PST 2016


On Thursday, 18 February 2016 at 22:46:04 UTC, Walter Bright 
wrote:
> On 2/18/2016 10:22 AM, Timon Gehr wrote:
>> He wanted to embed a mutable reference count literally within 
>> a const object.
>> Not a headconst object.
>
> I know. I pointed out how it could be done in a way to achieve 
> the same effect.
>
> BTW, shared_ptr<> uses a pointer to the ref count.

Could D RefCounted!T be splitted into data (possibly immutable) 
and mutable metadata?

struct MutablePart
{
     int rc;
     T cache;
     Mutex mutex;
}

class A
{
    int data;
    // Consider mutable(T)* works like const(T)*
    private mutable(MutablePart)* metadata;
    this() {metadata = new MutablePart}
}

immutable A a;
a.metadata.rc++;

This way instance of A could be in ROM and ref counter is mutable.

If A is const (and this way possibly immutable and shared) 
situation as bad as in case of storing metadata in an allocator. 
Field A.metadata should be shared in some cases and thread local 
in others. In fact D have to add possibly_shared type constructor 
to represent type of metadata for const data.

To make mutable field friendly with @pure, mutable field should be
1) unique. Mutual mutable treat like global.
2) private
3) allowed to update only with expression like:
     this.updateCache(mutable.cache);
     where:
         updateCache() is const and pure;
         updateCache depends only on "this";
         Mutable parameter marked as out;
     So for two identical objects cache will always be the same.
     It is impossible to do incremental caching or even reuse 
resources.
4) accessible only by property like this:
    ref const(Data) getData() pure

Ofc metadata of immutable should be shared.

So what other things breaks mutable like this:
muttable(MutablePart)* metadata;
?


More information about the Digitalmars-d mailing list