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?
A weak pointer is a smart pointer that does not take ownership of an object but act as an observer. In other words, it does not participate in reference counting to delete an object or extend its lifetime.
In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced only by weak references – meaning "every chain of references that reaches the object includes at least one weak reference as...
Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. References: A reference variable is an alias, that is, another name for an already existing variable.
Its destruction can cause a delete on the raw pointer. A weak pointer only knows the raw pointer, and whether or not it's still valid. It doesn't keep the raw pointer alive by existing and it can't make the raw pointer go away by being cleaned up.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With