引用计数类的库实现

问题描述 投票:1回答:1

我有一个这样的课:

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
};

所以我的问题是:标准/升级库中是否存在这样的方便类?或者,如果不实现我自己的引用计数,最好的方法是什么。

c++ boost std reference-counting
1个回答
3
投票

扩展我的评论。你需要Texture对象作为同一个ID的共享引用,所以它需要包含在一些引用计数类型中的ID才能保存Texture。这正是std::shared_ptr的一个用例。所有你需要的是一个custom deleter,它将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的copy / move / dtor现在可以由编译器隐式生成,因为它依赖于std::shared_ptr的正确行为。

© www.soinside.com 2019 - 2024. All rights reserved.