I have a few classes which do nothing except in their constructors/destructors. Here's an example
class BusyCursor
{
private:
Cursor oldCursor_;
public:
BusyCursor()
{
oldCursor_ = CurrentCursor();
SetCursor(BUSY_CURSOR);
}
~BusyCursor()
{
SetCursor(oldCursor_);
}
}
// example of use
void DoSlowThing
{
BusyCursor busy;
... do something time-consuming ...
}
I'm a little concerned about future readability. Am I being too "tricksy" here, with a variable ("busy") which is never actually used in the code? Could some static analysis tool suggest they be removed, or is this idiom sufficiently common not to worry about?
This technique is very common and is known as the design pattern: Resource Acquisition Is Initialization (RAII).
I would not hesitate to use this design pattern at all.
It's much better that you are coding using this design pattern because you will avoid bugs by forgetting to reset the cursor, or whatever the resource in question is.
If you are concerned that other programmers might not understand it, then those programmers should be more educated. Always strive to code in the most error free way where you make it impossible for you and others to shoot yourself/themselves in the foot.
"Could some static analysis tool suggest they be removed?"
The reason is because the object is created and the constructor/destructor are called. So it is not an unreferenced variable.
As others have said, this is good C++ style. To aid readability, I always prefix such RAII-only classes with Scoped
(for example, ScopedBusyCursor
) to make it clear from a glance what the class's purpose is.
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