构造函数导致段错误

时间:2016-01-30 02:12:38

标签: d

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;

1 个答案:

答案 0 :(得分:0)

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