I am trying to make an assignment operator for a texture wrapper in C++ but I have too many issues and I am not sure which to go by.
The structure looks like this:
class Texture
{
protected:
GLuint textureID; //!< OpenGL name of the texture
GLuint target; //!< Target of the texture (e.g GL_TEXTURE_2D)
int color_format; //!< The color format of the texture (e.g GL_RGBA)
int width; //!< width of the texture
int height; //!< height of the texture
std::string file;
public:
Texture(){}
Texture(std::string file_path, GLuint target);
~Texture();
};
There's a bit more to it but it's not important.
The problem comes specifically from the textureID
field. That value is the one returned by glGenTextures
, it's essentially a pointer for all given purposes.
When copying a texture I can't just copy the textureID
field. If I do this, when the other object gets deleted, the current object is also deleted, which will lead to unexpected behavior, bugs, segfaults and all things bad.
However, copying the texture each time is very slow, and also very painful to do as you have to manually copy each mipmap level and whatnot. I do care about efficiency a lot so I am trying to avoid actually copying the data.
I have a "bad" solution which is. Most of the time I don't need the old copy to remain, as I am mostly just re-instantiating the values of a texture.
In other words something like:
Texture t;
t = Texture(file1, target1);
t = Texture(file2, target2);
So my idea is to to set the textureID
field in the rvalue to 0 (nullptr
) before copying it.
Essentially this prevents shallow copies by invalidating the previous object. This is fast, allows me to do most of what I need, is easy to implement. But it's VERY misleading, since the statement
Texture t1, t2;
t1=t2;
Is also silently making t2
an invalid object.
What should I do?