1

I am currently doing some OpenGL stuff and I want to wrap an OpenGL buffer in a class like this:

class VertexBuffer
{
public:
    uint32_t id = 0;

    VertexBuffer()
    {
        glGenBuffers(1, &id);
    }

    ~VertexBuffer()
    {
        glDeleteBuffers(1, &id);
    }

    // more stuff to upload data, etc.
};

When the VertexBuffer class is constructed it creates the OpenGL buffer and stores the ID of it and once it gets out of scope the buffer will be deleted.

But what if something like this happens:

VertexBuffer buffer;

//...

VertexBuffer copy(buffer);

// copy gets passed around and buffer goes out of scope while copy still exists somewhere

Once buffer goes out of scope it deletes the OpenGL buffer (because of the destructor) but there is still the copy around which refrences the OpenGL buffer that just got freed.

An easy way of avoiding it is by using an std::shared_ptr but this seems a little bit "over the top", as VertexBuffer is more or less just a wrapper around an integer with an automatic clean up (destructor). Is there a better way or am I overlooking something?

Edit:

I have also thought about adding a static map with the key being the ID and the value being a count of VertexBuffers with this ID, but this seems also very un-elegant (works similar to a std::shared_ptr).

danwolb02
  • 41
  • 3
  • Assign a "special value" to it on release. check for the "special value" before releasing. As it is an integer, you probably can assing `zero` to it. – user14063792468 Dec 24 '20 at 22:58
  • After having a second thought, I did understand that the above does not work in your specific case. The variable gets out of scope and you get garbage in place of `id`. Well you better rethink your code structure or do a `reference counting`. – user14063792468 Dec 24 '20 at 23:02
  • @yvw Thats not really the problem. `copy` refrences freed memory (on the GPU); ID is not important. Reference counting would mean to use (something like) an `std::shared_ptr` but I want to avoid it. – danwolb02 Dec 24 '20 at 23:04
  • What I meant to say, is that, that if you use pointer(plain `C` pointer) to the `id` value, then... Then you can `destroy` it with assigning `NULL` to the `id`. I can't explain better. The point is that `OpenGL` is a state machine, and does not really maps as is to the Object Oriented Programming. `OpenGL`, as was stated somewhere in the reference pages, is aligned with a procedural paradigm. – user14063792468 Dec 24 '20 at 23:08
  • 1
    I would delete copy&move constructor/operator as I dont see why you would want those and it doesnt really tie into the way opengl is designed – Yamahari Dec 24 '20 at 23:16

0 Answers0