2016-01-30 76 views
1
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;

+0

等待,真正的功能實際上是空的嗎? –

+0

@ AdamD.Ruppe它最初並不是,但它也是一個空的身體段錯誤。 –

回答

0

問題是wref.ptr = null;因爲析構函數總是被調用和wref尚未分配任何價值的是,它會試圖訪問的當然結果nullptr在段錯誤。

相關問題