Boost logo

Boost :

From: Pavel Vozenilek (pavel_vozenilek_at_[hidden])
Date: 2002-12-08 06:26:32


Execute-once code block is usually implemented using idiom:

  static bool initialised1 = false;
  if (!initialised1) {
    initialised1 = true;
    ...
  }
  ...
      static bool initialised2 = false;
      if (!initialised2) {
        initialised2 = true;
        ...
      }

This is a bit low-level, quite error prone and verbose
and may be replaced by (macro based) equivalent:

  ...
  DO_ONCE x = new X;
  ...
      DO_ONCE
      {
        y = new Y;
        foo();
        ...
      }
  ...

Does anybody find it useful enough to consider inclusion
into boost/utility.hpp?

Macro definition (named BOOST_DO_ONCE):

#define BOOST_DO_ONCE_HELPER1(line) \
  boost_do_once_initialised_flag_##line##_
#define BOOST_DO_ONCE_HELPER2(line) \
  BOOST_DO_ONCE_HELPER1(line)
#define BOOST_DO_ONCE_HELPER3 \
  BOOST_DO_ONCE_HELPER2(__LINE__)

#define BOOST_DO_ONCE \
  static bool BOOST_DO_ONCE_HELPER3 = false;\
  if ((!BOOST_DO_ONCE_HELPER3) && \
      ((BOOST_DO_ONCE_HELPER3 = true) == true))

Notes:
  * Compiles on Intel C++ 6/7, Borland C++ 6,
    VC++ 6.5 (edit and continue must be switched off
    due to bug) and Comeau online.
  * The last line looks strange to avoid compiler warning.

/Pavel

_________________________________________________________________
The new MSN 8: advanced junk mail protection and 2 months FREE*
http://join.msn.com/?page=features/junkmail


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk