构造函数导致段错误

Constructor causes a segfault

struct OwnedRef(T){
    import std.typecons: Proxy;
    OwnedRefImpl!T* w;
    private this(OwnedRefImpl!T* w){
        this.w = w;
    }
    mixin Proxy!w;
}
struct OwnedRefImpl(T){
    import std.typecons: Proxy;
    static if (is(T:Object))
        alias RefT = T;
    else
        alias RefT = T*;
    private Owned!(T)* ptr;
    this(Owned!(T)* t){
        ptr = t;
    }
    bool expired(){
        return ptr == null;
    }
    auto ref get(){
        if (expired()){
            throw new Error("Access of expired OwnedRef.");
        }
        return ptr.get();
    }
    mixin Proxy!get;
}
struct Owned(T){
    import std.experimental.allocator;
    import std.typecons: Proxy;
    static if (is(T:Object)){
        alias RefT = T;
        @safe ref T get(){
            return ptr;
        }
    }
    else{
        @safe ref T get(){
            return *ptr;
        }
        alias RefT = T*;
    }
    this(Args...)(auto ref Args args){
        ptr = theAllocator.make!T(args);
        wref = new OwnedRefImpl!T(&this);
    }
    OwnedRef!(T) getRef()
    {
        return OwnedRef!T(wref);
    }
    ~this(){
        wref.ptr = null;
        theAllocator.dispose(ptr);
    }
    mixin Proxy!get;
    this(ref Owned!T oref){
        //memory corruption here
    }
    @disable auto opAssign(U)(U);
private:
    RefT ptr;
    OwnedRefImpl!T* wref;
}
void main()
{
    auto o1 = Owned!int(42);
    auto o2 = Owned!int(o1); //corruption here
}

这是类似于 Unique 但能够给出 weak references.

的超级简单实现

有问题的代码段似乎是

    this(ref Owned!T oref){
        //memory corruption here
    }

我不知道为什么这会导致段错误,我似乎没有访问任何无效内存。我唯一能想到的是我可能误用了 theAllocator.

更新:

问题似乎是 wref.ptr = null; 来自析构函数。

问题是 wref.ptr = null;,因为总是调用析构函数并且 wref 尚未分配任何值,它会尝试访问 nullptr,这当然会导致段错误。