Hi, I've been following the D language off and on for several years, have read Andrei's D book, but haven't ever posted here before. Mostly, I come from a C++ and C# background. Recently, I was playing with D using the derelict bindings for the SDL library.

The SDL library uses handles in the form of struct pointers for resource management. In C++ I like using unique and shared pointers to manage C handles. Additionally, I like being able to specify custom clean up functions for specific resources. For example:

typedef std::unique_ptr<HandleType, HandleDeleter> handle_ptr;

My question is: what's the status of D's struct Unique? It looks like struct RefCounted is current, but I can't tell with Unique. There's several comments in the source that say: doesn't work yet. It seems like some of it could be made to work as intended. For example, the commented out code to disallow construction via an lvalue:

// this(U)(ref Unique!(U) u) = null; // commented out
// this(this) = null;

Couldn't this be written:

@disable this(U)(ref Unique!(U) u);
@disable this(this);

Seems to work when I try it. It stopped the copy from working, but I can still do a move. Like this:

Unique!(int) i1 = new int;
Unique!(int) i2 = move(i1); // works!

Next, I'd like to be able to use a custom deleter. For example, a naive implementation I could write would be something like:

struct Unique2(T, string D = "delete")
{
...
    ~this()
    {
debug(Unique2) writeln("Unique destructor of ", (_p is null)? null: _p);
        if (_p !is null)
        {
            mixin(""~D~" (_p);"); // delete _p;
            _p = null;
        }
    }
...

So, I could do things like:

Unique2!(int, "free") i1 = cast(int*)malloc(int.sizeof); // lame example

A real implementation would allow more interesting deleters in the form of delegates, but I'm already stretching my D skillz.

Anyway, am I missing something here? Is there a better D language feature I'm not thinking about that provides the same functionality as C++'s std::unique_ptr<> with custom deleters; besides putting scope (exit) everywhere?

-Chris

Reply via email to