www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Allocating Heap/GC Storage upon Default Construction of RC Containers

reply =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
Is there any way to make a default constructor of a struct 
container allocate/initialize an internal pointer?

I need this in a container with RC behaviour similar to

struct Container
{
     this()    // this is currently forbidden:
     {
         _rcStore = emplace(cast(RCStore*)malloc(RCStore.size), 
null, 0);
     }

private:
     static struct RCStore
     {
         T* store;
         size_t refCount;
     }
     RCStore* _rcStore;
}

If I can't modify default construction in containers such as 
`Container` it is gonna behave in the same confusing way as empty 
AA's do for (novel) D developers. Namely that the assignment of 
uninitialized AA's has copy semantics and non-empty AA's have 
reference semantics.

I believe Andralex has spoken about this being a problem that 
should be fixed if possible.
Sep 21 2016
parent Andrei Alexandrescu <SeeWebsiteForEmail erdani.org> writes:
On 9/21/16 8:49 AM, Nordlöw wrote:
 Is there any way to make a default constructor of a struct container
 allocate/initialize an internal pointer?

 I need this in a container with RC behaviour similar to

 struct Container
 {
     this()    // this is currently forbidden:
     {
         _rcStore = emplace(cast(RCStore*)malloc(RCStore.size), null, 0);
     }

 private:
     static struct RCStore
     {
         T* store;
         size_t refCount;
     }
     RCStore* _rcStore;
 }

 If I can't modify default construction in containers such as `Container`
 it is gonna behave in the same confusing way as empty AA's do for
 (novel) D developers. Namely that the assignment of uninitialized AA's
 has copy semantics and non-empty AA's have reference semantics.

 I believe Andralex has spoken about this being a problem that should be
 fixed if possible.
Sadly, not currently. I realize this makes certain designs more difficult. -- Andrei
Sep 22 2016