引用计数类的库实现
library implementation for reference counting classes
我有一个这样的类:
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
的正确行为。
相关文章:
- 如何在c++中使用引用实现类似python的行为
- 引用计数类的库实现
- unique_ptr实现接口时对已删除函数的引用
- 在函数重载中将右值引用实现为参数
- 对具有实现的函数的未定义引用
- 按值/引用传递定义的实现还是行为明智
- 函数描述与C++引用上的可能实现
- 从用户定义的头文件调用函数时出现未定义的引用错误,其实现位于.cpp文件中
- 引用计数智能指针的正确实现
- std::shared_ptr<std::string const> 可以作为引用计数的不可变字符串的有效实现吗?
- 在实现OpenSceneGraph时在Qt中获取引用问题
- 在我的C++链表实现中取消引用节点指针,给出意想不到的结果
- 使用const_cast const-ref getter 实现引用获取器的陷阱
- 如何为具有自引用指针的类实现复制构造函数/赋值运算符
- 尝试实现通过引用传递的向量以与二叉树一起使用,我错过了什么
- 如何在不使用指针的情况下实现引用中的链表
- 使用 C++ 实现引用计数
- 实现引用计数
- 是否可以在没有指针的情况下实现引用传递
- 持有大共享状态的访问者类:实现引用语义的最佳方式