[英]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? 如果我有一个对象
atype obj
,其中atype
的定义类似于typedef struct myType {...} * atype
,有什么方法可以获得对obj
所有引用,或者至少有多少引用?
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.
欢迎使用变通方法和替代方法。
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. 但是你可以实现一个自动增加计数器的
ref
函数,以及一个递减计数器的unref
函数。
a.obj = ref(obj);
/* ... */
a.obj = something_else;
unref(obj);
And that counter can be something external to any of the struct
s. 并且该计数器可以是任何
struct
外部的东西。 For example, you could use a hash table to keep track of pointer - counter relationships. 例如,您可以使用哈希表来跟踪指针 - 计数器关系。
You can also look into gobject
which provides this via g_object_ref
/ g_object_unref
. 您还可以查看通过
g_object_ref
/ g_object_unref
提供此功能的gobject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.