引用计数类的库实现

library implementation for reference counting classes

本文关键字:实现 引用      更新时间:2023-10-16

我有一个这样的类:

Texture
{
int ID
public:
Texture(std::string name){ ID = make_texture(name); }
~Texture(){ delete_texture(ID); }
};

但问题是当我移动类时,会调用析构函数,因此 ID 现在无效。

我目前的实现是这样的:

Texture
{
static std::unordered_map<int> m;
int ID
public:
Texture(std::string name){
ID = make_texture(name);
m[ID]++;
}
Texture(Texture& obj){ *this = obj; }
Texture &operator=(Texture& obj){
ID = obj.ID;
m[ID]++;
}
~Texture(){
if (!--m[ID])
delete_texture(ID);
}
};
//was coded in stack overflow so syntax may be a bit off

但真正好的是我可以继承的类,例如:

Texture : public ref_count<int>
{
int ID
public:
Texture(std::string name){ ID = make_texture(name); }
key(){return ID;} // inherited from ref_count
on_delete(){ delete_texture(ID); } // inherited from ref_count
};

所以我的问题是:标准/提升库中是否存在像这样的方便类?或者,在不实现我自己的引用计数的情况下实现这一目标的最佳方法是什么。

扩展我的评论。你需要Texture对象是同一ID的共享引用,所以ID需要包装在某种引用计数类型中,以便Texture保存。这正是std::shared_ptr的一个用例。您只需要一个自定义删除程序,它将delete_texture释放托管整数的一部分。

class Texture
{
std::shared_ptr<int> ID;
public:
Texture(std::string name) :
ID{ new int(make_texture(name)),
[](int* id_ptr) {
delete_texture(*id_ptr);
delete id_ptr;
}
}
{}
};

仅此而已。Texture的复制/移动/dtor现在可以由编译器隐式生成,因为它依赖于std::shared_ptr的正确行为。