Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const correctness -- C API shim layer

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.

like image 939
user2184879 Avatar asked Mar 20 '13 03:03

user2184879


1 Answers

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.

like image 173
John Zwinck Avatar answered Sep 30 '22 10:09

John Zwinck