Creating a reference counted type?

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 12 07:45:12 PDT 2016


this won't work at all. let's insert `writeln("FREE!");` in dtor, 
and test it:

auto foo (Foo foo) {
   version(dump) writeln(foo._refCount);
   return foo;
}

void main () {
   auto f = foo(Foo());
   version(dump) writeln(f._refCount);
}

it prints "FREE" once, so it looks like the whole thing is 
working. but now let's try this with `-version=dump`:

1
FREE!
2

ahem... wut?! we have one copy of our struct freed half the way, 
and another copy has refcount of 2, so it won't be freed at all. 
it doesn't so innocent as it looks: we may try to use `f` in 
`main`... just to find out that resources was mysteriously freed, 
and refcount is total garbage.


More information about the Digitalmars-d-learn mailing list