atilaneves / automem

C++-style automatic memory management smart pointers for D
BSD 3-Clause "New" or "Revised" License
86 stars 15 forks source link

Crash with RefCounted #38

Closed jpf91 closed 4 years ago

jpf91 commented 4 years ago

Probably a user error, but shouldn't this code be correct?

/+ dub.sdl:
       dependency "automem" version="~>0.6.1"
 +/

import automem;

void main()
{
    auto rc = RefCounted!S();
    for (auto r2 = rc; !r2.empty; r2.popFront)
    {
    }
}

struct S
{
    int front = 0;
    void popFront(){front++;}
    @property bool empty(){return front > 100;}
}
atilaneves commented 4 years ago

Simpler reproduction:

@safe unittest {
    static struct S {
        int front = 0;
    }
    auto rc = RefCounted!S();
    rc.front.should == 0;
}

The reason is that rc is in its T.init state. The code is definitely not correct, but I agree that it would be more user-friendly to get an exception/error instead of a segfault.

atilaneves commented 4 years ago

I just realised that TRWTF here might be that one doesn't get a valid (deref'able) RefCounted when constructing it with no arguments (it's a struct, so it's RefCounted.init at that point). I have to think about this.

atilaneves commented 4 years ago

After trying to fix this in code, I realised that both Unique and RefCounted have a static construct member function which should be used in these cases.