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 VertexBuffer
s with this ID, but this seems also very un-elegant (works similar to a std::shared_ptr
).