Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

idioms

raii

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?

like image 211
Roddy Avatar asked Jan 12 '09 12:01

Roddy


2 Answers

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.

like image 106
Brian R. Bondy Avatar answered Oct 05 '22 18:10

Brian R. Bondy


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.

like image 38
Josh Kelley Avatar answered Oct 05 '22 18:10

Josh Kelley