Greg
Greg

Reputation: 9168

C get all references to object?

If I have an object atype obj where atype is defined like typedef struct myType {...} * atype, is there any way I can get all the references to obj, or at least how many there are?

Something like:

atype obj;
... // Allocate

aStruct a;
a.obj = obj;

aStruct b;
b.obj = obj;

int refs = get_references(obj); // refs should now = 2

Any ideas? Workarounds and alternative methods welcome.

Upvotes: 0

Views: 65

Answers (1)

cnicutar
cnicutar

Reputation: 182664

No, there's no implicit way. But you could implement a ref function that automatically increases a counter, and an unref function to decrement it.

a.obj = ref(obj);

/* ... */
a.obj = something_else;
unref(obj);

And that counter can be something external to any of the structs. For example, you could use a hash table to keep track of pointer - counter relationships.

EDIT

You can also look into gobject which provides this via g_object_ref / g_object_unref.

Upvotes: 2

Related Questions