简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM