c++ - 引用计数类的库实现
问题描述
我有这样的课:
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
};
所以我的问题是:标准/boost 库中是否存在这样的便捷类?或者在不实现我自己的引用计数的情况下实现这一目标的最佳方法是什么。
解决方案
扩展我的评论。您需要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;
}
}
{}
};
就是这样。的 copy/move/dtorTexture
现在可以由编译器隐式生成,因为它依赖于std::shared_ptr
.
推荐阅读
- ios - UICollectionVIew 中未显示相机捕获的图像,如何显示从 UICollectionView 捕获的图像?
- ios - 如何访问 Google Drive API 中受限制的音频文件以在 AVPlayer (Swift 5) 中播放它们
- javascript - SQL Server 时间格式不等于客户端时间格式
- r - 如何使用 ggplot 在多面图中自定义背景颜色
- typo3 - 删除 TYPO3 加载页面
- python - 如何正确地使 AES.encrypt 包含 Python3 中的控制字符
- android - 更新到 Android Studio 4.1 时出现 java.lang.AssertionError
- javascript - 使用jquery选择复选框后表单按钮不起作用
- python - 在循环中合并两个数据帧但 TypeError: unhashable type: 'list' after first loop
- php - 当用户不验证 recaptcha 时无法生成错误响应