Theo Walton
Theo Walton

Reputation: 1105

library implementation for reference counting classes

I have a class like so:

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

but the problem is that when I move the class, the destructor is called so the ID is now invalid.

my current implementation would be something like:

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

but what would really be nice is a class I could inherit from like:

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

so my question is: does a convenient class like this exist in the standard / boost library? Or what is the best way to achieve this without implementing my own reference counting.

Upvotes: 1

Views: 92

Answers (1)

To expand on my comment. You need Texture objects to be shared references to the same ID, so it's ID that needs to be wrapped in some reference counting type for Texture to hold. That's exactly a use case for std::shared_ptr. All you need is a custom deleter that would delete_texture as part of freeing the managed integer.

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

And that's it. The copy/move/dtor of Texture can now be implicitly generated by the compiler, since it relies on the correct behavior of std::shared_ptr.

Upvotes: 3

Related Questions