7
votes

How does D manage ownership of objects? For example I need to express the following:

1.) Allocate an object
2.) Give out references/pointers
3.) If the initially allocated object is deleted, 
    all references/pointers should become inaccessible.

In C++ this is possible with std::shared_ptr + std::weak_ptr. Is this also possible in D?

1
See dlang.org/spec/garbage.html to get an better understanding how you can control the life time of objects. - key_
@key_ Are you sure that you have posted the correct link? I can not find anything related to life time management. - Maik Klein
You'll want to implement a sealed reference then keep pointers to pointers whenever you hand one out. Those pointers will want to be aware of their own lifetime to remove themselves from the list... there's a fair amount of overhead involved. Weak references themselves are easy - just make a pointer which the GC doesn't scan, or don't increase your refcount - but invalidating them when the object is deleted is harder. - Adam D. Ruppe
Yes the link is correct, it gives information how the garbage collector works. See section "Interfacing Garbage Collected Objects With Foreign Code". To summarize gc will free the memory for you when it can see no more reference. - key_

1 Answers

2
votes

At the moment there is no good implementation of weak references in D.

Please check these two forum threads:

Incorrect or "almost" correct implementations:

The biggest problem is that you need a GOOD API around weak references. Java and .NET have it, and it is arguably BAD. For a good reason - it is hard to come up with a good api!