Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak references or pointers

Tags:

d

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?

like image 575
Maik Klein Avatar asked Jan 17 '16 13:01

Maik Klein


People also ask

What is weak pointer in C++?

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.

What is weak reference in C++?

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...

What is the difference between a pointer and a reference?

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.

What happens to a weak pointer when it is destroyed?

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.


1 Answers

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

Please check these two forum threads:

Incorrect or "almost" correct implementations:

  • https://github.com/D-Programming-Language/phobos/blob/7134b603f8c9a2e9124247ff250c9b48ea697998/std/signals.d
  • https://github.com/lycus/mci/blob/f9165c287f92e4ef70674828fbadb33ee3967547/src/mci/core/weak.d
  • https://github.com/phobos-x/phobosx/blob/d0cc6b45511465ef1d493b0d7226ccb990ae84e8/source/phobosx/signal.d
  • https://bitbucket.org/denis-sh/unstandard/src/cb9a835a9ff5/unstd/memory/weakref.d

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!

like image 150
DejanLekic Avatar answered Oct 13 '22 10:10

DejanLekic