[Dlang-study] [lifetime] Few root decisions to take on RC classes

Michel Fortin michel.fortin at michelf.ca
Thu Nov 5 18:44:39 PST 2015


Le 5 nov. 2015 à 9:55, Marc Schütz <schuetzm at gmx.net> a écrit :
> How about this, though?
> 
> struct Droppable(T) {
>    T payload;
>    void delegate(const(T)* object) dropper;
>    alias payload this;
>    @disabled this(this);
>    ~this() {
>        if(dropper) dropper(payload);
>    }
> }
> 
> class Exception {
>    Droppable!string msg;
>    // ...
> }
> 
> I think this is a very useful pattern. We can then add helpers that convert GC, RC, Unique or otherwise managed objects that create Droppable wrappers from those, setting the dropper to a function that decrements the refcount, directly releases the memory, or is a no-op. And because the dropper is a delegate, it can even be a member of an allocator.

But how do you prevent the payload from being leaked in a way that it outlives the droppable? For instance, someone might want to log the exception message and put it into a queue for a separate logging thread to process. You're giving raw access to the string, so it's very easy mess things up if you are not careful.

-- 
Michel Fortin
michel.fortin at michelf.ca
https://michelf.ca




More information about the Dlang-study mailing list