Alex Rivera | Logout

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

Asked 2009-01-12T12:50:21.310
9

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?

Edit
Report

1 Answer

4

It's a good idiom and commonly used.

It's better than any alternative, for example even if your something time-consuming code throws an exception, the ~BusyCursor destructor will still be called.

answered 2009-01-12T12:57:51.763

Your Answer