0

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?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Makogan
  • 8,208
  • 7
  • 44
  • 112

1 Answers1

1

Delete the copy constructor and copy assignment operators. Define appropriate move operations.

Add a Reset or Rebind member to replace an existing texture with a new one

t.Reset(file1, target1);

to avoid creating a temporary object that gets copied/moved then destroyed.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56