[英]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: 以下类封装了缓冲区的OpenGL名称,并提供了一些用于更改缓冲区状态的方法:
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
. 这些方法都没有改变BufferObject
对象的状态,所以它们都可以用const
声明。 However, dataStore
and mapBufferRange
both call OpenGL methods which change the state of the object on the GPU ( glBufferData
and glMapBufferRange
, respectively). 但是, dataStore
和mapBufferRange
都调用OpenGL方法,这些方法改变了GPU上对象的状态(分别是glBufferData
和glMapBufferRange
)。 I would like to declare them without const
to indicate that they are modifying the state on the GPU. 我想声明它们没有const
表示它们正在修改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. 虽然没有严格的规则,但“尽可能使用const
”绝对不是通用的方法。 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). 请参考std::vector::operator[]
类的函数 - 它不会更改vector
对象的成员,但仍提供非const
版本(以及不同的const
版本)。
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&
. 查看这个的一个好方法是:假设你有一个BufferObject
,并将它传递给一个带有const BufferObject&
的const BufferObject&
。 Will it mess up your expectations (invariants you expect to hold) if that function calls dataStore()
? 如果该函数调用dataStore()
,它会弄乱你的期望(你期望持有的不变量dataStore()
吗? If so, do not mark dataStore()
as const
. 如果是这样,请不要将dataStore()
标记为const
。
To address your particular case, I think you're correct and should leave these functions non- const
. 为了满足您的特定情况下,我认为你是正确的,应该让这些功能的非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. 虽然它们不修改C ++对象的物理内容,但它们确实修改了该C ++对象所表示的实体的逻辑状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.