Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare a method const, when underlying OpenGL state is modified

The following class encapsulates the OpenGL name of a buffer and provides a few 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 object, so they could all be declared with const. However, dataStore and mapBufferRange both call OpenGL methods 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 are modifying the state on the GPU.

What is the best practise to follow in this situation?

like image 507
Nelarius Avatar asked Feb 19 '15 09:02

Nelarius


1 Answers

You're right that since they don't modify the actual state of the object itself, you can choose.

While there is no hard-and-fast rule, "use const wherever possible" is definitely not the universal way to go. Refer to functions like std::vector::operator[]—that doesn't change the members of the vector object, but stills provide a non-const version (and a different const version).

One good way of looking at this is: assume you have a BufferObject, and you pass it to a function which takes a const BufferObject&. Will it mess up your expectations (invariants you expect to hold) if that function calls dataStore()? If so, do not mark dataStore() as const.

To address your particular case, I think you're correct and should leave these functions non-const. While they don't modify the physical contents of the C++ object, they do modify the logical state of the entity represented by that C++ object.

like image 194
Angew is no longer proud of SO Avatar answered Oct 20 '22 01:10

Angew is no longer proud of SO