Question

What are the relevant practices for ensuring const-correctness when writing classes that serve as wrappers to other library (C style) APIs. I was in the process of writing a class (Renderer) that translates app specific render calls to corresponding OpenGL(and perhaps DirectX later) calls. This class doesn't actually have its own state that is modified by calls to, say, Renderer::applyTransform(const Matrix&), but is internally calling APIs that alter OpenGL's state. In this case, is marking such APIs as const the correct thing to do, or does the "modifies observable state" also extend to the OpenGL state that this class wraps, requiring me to make it non-cost?

This is similar to Const-correctness and hardware writes, but perhaps this is a more specific use-case.

Was it helpful?

Solution

If you're calling C functions that take your member variables by non-const pointer, those wrapper functions should probably not be const. If they're only observing state and not modifying it, you can make your methods const--even if the C API is not const-correct you can use const_cast<> or mutable on your member variables as needed.

Think about it in terms of the semantics--if a method doesn't alter the state of the world, make it const. If it does alter the state of the world, it probably shouldn't be const, unless the altered state is something like a cache where it's only an optimization that results in the alteration and not something essential.

OTHER TIPS

Are you required to make them non-const? No.

Would it be a good idea, if the semantics are that the effective state would be modified? Probably yes, but it depends on your overall design.

A method is just a function, and this is just another function parameter. Any parameter can be a pointer to const, this only affects the corresponding argument and has nothing to do with the function modifying any other argument or global state.

So yes, a const method can modify global state, nothing wrong with that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top