【发布时间】:2013-09-19 17:20:04
【问题描述】:
我正在编写一个库,其中另一种语言的连接库只能理解 C。我需要类似于 std::shared_ptr 的东西,其中所有权是共享的。在我的情况下,手动引用计数是可以的。
C11 supports atomic operations。我一直在尝试找到一个如何正确执行此操作的示例,但我能够找到的每个示例都与 C++11 有关,它具有运算符重载。
基本上我想做的是这样的:
typedef struct {
union {
int integer;
// ...
char* cstring;
void* ptr;
};
enum {
Undefined,
Integer,
String,
// ...
} type;
int* refcount;
} value;
void value_retain(value v) {
++(*v.refcount);
}
void value_release(value v) {
if(--(*v.refcount) == 0) {
// free memory, depending on type...
}
}
我假设我需要将int* 更改为atomic_int*。函数atomic_fetch_sub 表示它返回“先前保存的值是obj 指向的原子对象。”。这让我相信我的函数应该是这样的:
void value_retain(value v) {
atomic_fetch_add(v.refcount, 1);
}
void value_release(value v) {
if(atomic_fetch_sub(v.refcount, 1) == 1) {
// free memory, depending on type...
}
}
这是否正确?我担心atomic_fetch_sub 返回的值是是,而不是值是。
还有memory_order 是什么意思,我应该使用什么来进行引用计数?有关系吗?
【问题讨论】:
标签: c reference-counting c11