Search code examples
c++idiomsraii

Good or Bad C++ Idiom - Objects used purely for constructor/destructor?


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?


Solution

  • 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?"

    • No static analysis tool will see this as a problem.
    • No compiler warning will be given
    • No compiler optimization will cause any problems.

    The reason is because the object is created and the constructor/destructor are called. So it is not an unreferenced variable.