views:

32

answers:

2

What are the differences between weak and unowned references in Vala.

Based on what I've learned from Vala tutorials both weak and unowned references are not counted, and when the real instance goes out of scope they will refer to null(!!).

Why there should be tow distinct means for one reason?(if they do the same job) If not, could someone give me a simple example to show why and when we have to use each of them?!

Thanks a lot

A: 

Caveat: I know nothing about Vala (until 5 minutes ago)

There seems to be a really good introduction to Vala's Reference Handling here

Non reference counted objects may have only one strong reference (think of it as the "master" reference). When this reference goes out of scope the object is freed. All other references must be unowned references. When these references go out of scope the object will not be freed.

Whereas weak reference don't prevent an object from being garbage collected it appears to me that unowned references are the opposite, ie. the object will only ever have one reference but the object is never collected.

Preet Sangha
there is no garbage collector in Vala, it only uses reference counting to prevent performance degradation.
SepiDev
hence weak and unowned seem to be the same concept, but when you use each of them the result could be changed in some situation!!!
SepiDev
Reference counting is still garbage collection ...
Guillaume
+1  A: 

There is no difference between the two right now. The language developers chose two distinct keywords to indicate the possibility that there may be a difference in the future, see this quote from the documentation:

At the moment weak and unowned can be used interchangeably. However, you should use weak only for breaking reference cycles and unowned only for ownership issues as described above.

Weak references are used, as far as I can see, on GLib.Object subclasses, and unowned references are used on non-reference-counted ("compact" in Vala terminology) classes imported from non-GObject C libraries. There are examples on the documentation page I linked to above.

ptomato