[Dlang-study] [lifetime] Few root decisions to take on RC classes
Marc Schütz
schuetzm at gmx.net
Thu Nov 5 06:55:06 PST 2015
On Thursday, 5 November 2015 at 13:12:20 UTC, destructionator
wrote:
> On Thu, Nov 05, 2015 at 11:19:11AM +0000, Marc Schütz wrote:
>> Just Throwable being @rc isn't enough. Exceptions contain
>> additional data, at the least a message, which is often
>> dynamically generated.
>
> That's a bad pattern we should discourage though. Generating a
> string for an exception makes for less useful exceptions
> (extracting data from them is harder) and is just generally
> wasteful because you can avoid it.
The message was just the most glaring example, but it applies to
other members as well.
>
> Instead, we should be making exception subclasses that hold the
> data you'd use to generate that string. Those would be
> user-defined and managed however the data themselves would
> be... so the Exception destructor is responsible for destroying
> them if structs or other RC items, or leave them behind for the
> GC, or whatever.
This is not a nice solution for Phobos exceptions, though. It
requires transferring ownership of data to the exception. For the
message member, this means that you have to call .idup if you
want to pass a string literal or a string that you actually want
to be garbage collected.
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.
More information about the Dlang-study
mailing list