Boost logo

Boost :

From: Ashot Nakashian (AshotN_at_[hidden])
Date: 2002-08-12 03:00:40

Static objects in functions are very handy for recursion and for
lazy-construction of the objects. It's the "create once (on demand) use
many" mechanism, from the users perspective. But sometimes the object in
question is expensive to keep in memory when it is no longer needed.
Cases where certain functions are called rarely and when they are done,
they *know* they don't need the static object(s) they created, probably
until the function is invoked again. I'm assuming that the function
needs static object(s) for its internal use/algorithm, and it will
utilize them only when it calls itself, but expects the static object
creation mechanism to kick in when the static object(s) are not created.
This is one of possibly many scenarios where one needs to have static
objects _on-demand_, i.e. where the static object is destructible, and
thus re-constructible.
I'm suggesting, if there exists no similar mechanism in boost, the
addition of a class that is responsible for the above-mentioned
mechanism. I'll do all the hard work ;) I'm brainstorming right now for
a simple and elegant solution, so if you have any ideas, start typing...
Here is an example of what I'm talking about, nothing final, just a
// Memory intensive class.
Class MyStaticOb {};
void func()
      // boost::staticOb() will be called only once.
      static boost::staticOb<MyStaticOb> myOb; // really static object
      // look below for the imp of create().
      If (myOb.create() == false)
      // my complicated, reentrant algorithm.
      While (something_interesting)
            // do a lot of good work using myOb
            // overloaded -> operator
            if (i_like_to)
                  func(); // call myself.
      // no longer needed.
// Assume boost namespace, this is the static object class
template <typename T>
class staticOb
      // the actual object
      T* ptr;
      // ctor
      staticOb() : ptr(0)
      // dtor, if the user forgot to destroy. Compiler generated on
            { destroy(); }
      bool create()
            { if (!ptr) ptr = new T; return (bool)ptr; }
      void destroy()
            { if (ptr){ delete ptr; ptr = 0; } }
      T* operator -> ()
            { return ptr; }
I think in cases where MyStaticOb uses a lot of memory and is used
rarely (say this func() is usually called but only once) and I need not
keep it in memory, it's worth the overhead of calling create(), after
all it's a simple inline function that ends up executing a simple if
The gains are: Trade MyStaticOb's static memory with the one used by
And the losses: Check for ptr, and check for create()'s success.
Any suggestions and/or criticisms are -more than- welcome.

Boost list run by bdawes at, gregod at, cpdaniel at, john at