Should I declare a const method when the underlying state of OpenGL changes

The following class encapsulates the OpenGL name for the buffer and provides several methods for changing the state of the buffer:

class BufferObject { public: explicit BufferObject( GLenum type ); virtual ~BufferObject(); // some methods omitted void dataStore( GLsizeiptr size, const GLvoid* data, int usage ); void* mapBufferRange( GLintptr offset, GLsizeiptr length, int accessFlag ); void unmapBuffer() const; private: GLuint object_; }; 

None of these methods change the state of the BufferObject , so they can all be declared with const . However, dataStore and mapBufferRange both calls to the OpenGL method, which change the state of the object on the GPU ( glBufferData and glMapBufferRange , respectively). I would like to declare them without const to indicate that they change state on the GPU.

What is the best practice in this situation?

+6
source share
1 answer

You are right, since they do not change the actual state of the object itself, you can choose.

While there is no hard and fast rule, โ€œusing const where possibleโ€ is definitely not a universal way. Refer to functions like std::vector::operator[] & mdash, which do not change the members of the vector object, but fixed objects provide a non- const version (and a different version of const ).

One good way to take a look at this: suppose you have a BufferObject , and you pass it to a function that takes const BufferObject& . Will this ruin your expectations (the invariants you expect to spend) if this function calls dataStore() ? If so, do not dataStore() as const .

To answer your specific case, I think you are right and should leave these functions not const . Although they do not alter the physical contents of a C ++ object, they alter the logical state of the object represented by this C ++ object.

+4
source

Source: https://habr.com/ru/post/982727/


All Articles