Suppose I have an RAII-style C++ class:
class StateSaver
{
public:
StateSaver(int i) { saveState(); }
~StateSaver() { restoreState(); }
};
...to be used like so in my code:
void Manipulate()
{
StateSaver save(1);
// ...do stuff that modifies state
}
...the goal being to enter some state, do stuff, then leave that state when I leave that scope. Is there a way to make this typo not compile (or warn, or somehow complain so that the mistake can be noticed)?
void Manipulate()
{
StateSaver(1); // ruh-roh, state saved and immediately restored!
// ...do stuff that modifies state
}
I'm not aware of anything in C++ itself which I could use to prevent this, but that doesn't mean it doesn't exist. If there isn't anything in C++, compiler-specific extensions would be acceptable. I'm primarily interested in anything targeting gcc and msvc (someday icc, ideas for other compilers welcome but less likely to be useful) so hacks for any of them would be useful (abstracted into appropriately #ifdef'd macro definitions, of course).
I'm not sure if anything can be done at compile-time. For a run-time check, you could do this:
struct SaveMatrix
{
SaveMatrix(const SaveMatrix& that) {
assert(this == &that);
glPushMatrix();
}
~SaveMatrix() { glPopMatrix(); }
};
Which requires the client to write:
SaveMatrix sm(sm);
and there's no way to do the same for a temporary without binding it to an identifier (at which point it's no different from an auto variable).
SaveMatrix save();
doesn't define an object either. It declares a function.
There's very little you can do to prevent others (or yourself, FTM) from doing something else than they wanted to. The only thing I can think of is not writing the code itself, but writing a macro instead.
#define SAVE_MATRIX SaveMatrix save ## __LINE__
However, this is quite ugly. OTOH, it does catch the error at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With