Re: Floating references

6.06.2017 11:50 Stefan Salewski <mail ssalewski de> wrote:
But I was wondering, why for newly created objects ref count is not
just zero, so when the element is put into a container it is just
increased to one.

So there must be a reason why it can not work this way. Of course when
ref count drops to zero the element is deleted. But when a newly
created element just has ref count zero, where is the problem?

Let's consider a system where a newly created object has ref count zero.
Assume that you have created an object but changed your mind and
decided you want to delete it. g_object_unref() raises an assert
if ref_count is not > 0. But OK, this assert would have to be removed.
So having ref_count == 0 you can't delete the object because ref_count
is already 0. Or if you allow ref_count to be decremented, as ref_count
is of type guint it would become 0xFFFFFFFF rather than -1.

Then assume that g_object_ref() was called once. The next balanced
g_object_unref() would make the object deallocated. You would have
to call g_object_ref() immediately after creating to make sure the
object exists until you decide to deallocate it.

With floating object you can (you have a choice):

- ref/unref the object any number of times as long as the number
  of unrefs is never greater than the number of refs,
- give an ownership to a container and forget the unref (the container
  will take care of it),
- unref the object to delete it.

It looks like a good design to me. Even if a better system can be
designed I believe it would not be much better and therefore not
worth reworking.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]