News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

c++ tips - Useful constructor/destructor side-effects

Started by ben2ong2, October 07, 2006, 03:54:29 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

PROBLEM: The constructor-destructor pair for an object can be used
to improve code quality, particularly maintenance.


RESPONSE: Allan Clarke

Designers should consider that useful work can be performed by classes
in their constructor-destructors. Functions or methods which perform
a task upon entry and undo that on exit can benefit from this technique.

By throwing the burden of calling the "undo" code onto the
compiler, the code becomes more robust and more maintainable.
For example a maintenance change might involve inserting a
conditional return into the function.

// ................................................................

An example, using Guide code is shown below. In this simple class,
the constructor changes the cursor to a new style, but remembers
the current cursor. Upon destruction, the old cursor is restored.

(Note that this is not a "heavy-weight" TObject descendent, but is
so simple as to be completely inlined, hence the naming scheme in
which the class name begins with "S".)

class SCursorPush {
  private:
   int fSaved;
  public:
   SCursorPush (int newCursor) {
      fSaved = gScreen->cursorStyle();
      SETCURSORSTYLE (newCursor);
   }

   ~SCursorPush () { SETCURSORSTYLE (fSaved); }
};

void myOldFunction ()
{
    int savedCursor = gScreen->cursorStyle();
    SETCURSORSTYLE (g_resizeCurs);

    .... do some work

    SETCURSORSTYLE (savedCursor);
}

void myNewFunction ()
{
    SCursorPush (g_resizeCurs);

    .... do some work
}

// ................................................................


You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login