Const correctness

I’m making C++ wrapper classes, and while making some member functions const, I noticed that
the RenderCopy family of functions take a non-const renderer & texture as parameters. Now, it seems to me that this operation should not modify either of these two (I mean, it literally has copy in the name), but I’d like to ask here, just to be sure. Is this a case of “const-wrongness” or is there a valid reason for these not being passed as const?

If you dig into the source code, the SDL_RenderCopy function passes the texture pointer to SDL_RenderCopyF.

I don’t know what these following lines do exactly*, but it’s found in the SDL_RenderCopyF, and it modifies the texture that you originally passed to SDL_RenderCopy:

    if (texture->native) {
        texture = texture->native;
    texture->last_command_generation = renderer->render_command_generation;

A member of the texture is being modified, so it can’t be const.


  • texture->native has something to do with the native pixel format and conversion from/to the format that you originally requested in SDL_CreateTexture().
  • The variables in the lowest line are later used to confirm that the texture is required by the current rendering queue/frame and the renderer should be flushed before continuing.

Side Note:

SDL_RenderCopy is not a “copy” in the C++ sense of the term, in SDL3 this function is renamed to SDL_RenderTexture which may help clear up the terminology.

If your design requires const member functions I think it’s fine to designate such members as mutable.
But logically renderer can’t be const, because what you are actually doing is rendering, i.e. making changes to the something rendered. And about texture, changes to these parameters (in SDL_RenderCopy) have no real side-effect on subsequent renderer usage - which within your application can be seen as immutability.

If the class contains a pointer you don’t need to mark it as mutable to be able to pass it to SDL_RenderCopy inside a const member function because the compiler only apply the constness on the pointer itself, not to the thing that the pointer points to.

1 Like

Oh, okay, thank you. In that case, I’ll have the renderer’s draw operations be non-const, taking a const texture&, so as to have it be semantically correct (not sure if that’s the right term).

Yeah, I was wondering why that’d compile. I was slightly scared that this would introduce UB, as I’m telling the compiler that the object is const while it’s actually potentially getting modified. Glad I’ve got that cleared up.