In OpenGL, one often writes code like this:
glPushMatrix();
// modify the current matrix and use it
glPopMatrix();
Essentially, the state is changed, then some actions are performed that use the new state, and finally the state is restored.
Now there are two problems here:
- It's easy to forget to restore the state.
- If the code in between throws an exception, the state is never restored.
In true object-based programming style, I have written some utility classes to overcome these problems, like so:
struct WithPushedMatrix {
WithPushedMatrix() { glPushMatrix(); }
~WithPushedMatrix() { glPopMatrix(); }
};
Now I can simply write my previous example like this:
WithPushedMatrix p;
// modify the current matrix and use it
The exact moment of restoring is determined by the lifetime of p
. If an exception is thrown, p
's destructor gets called, the state is restored, and life is good.
Still, I'm not entirely happy. Especially if the constructor takes some arguments (e.g. flags for glEnable
), it's easy to forget to assign the object to a variable:
WithEnabledFlags(GL_BLEND); // whoops!
The temporary gets destroyed immediately, and the state change is reversed prematurely.
Another issue is that anyone else reading my code might get confused: "Why is there a variable declared here that is never used? Let's get rid of it!"
So, my questions: Is this a good pattern? Does it maybe even have a name? Are there any problems with this approach that I'm overlooking? Last but not least: are there any good alternatives?
Update: Yes, I guess it's a form of RAII. But not in the way RAII is normally used, because it involves a seemingly useless variable; the "resource" in question is never accessed explicitly. I just didn't realize that this particular usage was so common.