Boost logo

Boost :

From: Jason Hise (chaos_at_[hidden])
Date: 2005-01-26 11:13:25


Jason Hise wrote:

> Alright... I believe that my multiton dependency lifetime is
> functional based on a few simple tests. However, I could easily be
> wrong, so I would appreciate the efforts of everyone who tries to
> break my code. My next task will be to try a multiton longevity
> lifetime policy, and then perhaps I'll try to find a way to make
> GetInst accept multiple keys. The code at
> http://boost-sandbox.sourceforge.net/vault/ under Singleton is up to date.

I just realized that I should probably at least provide a small sample
program so that people can see how the multiton is intended to be used.
In the following example, a unique country can exist for each unique
name, a unique state can exist for each unique name, and states depend
upon the country "USA".

#include <string>
#include <Multiton.h>
using namespace boost::singleton;

class Country : public Multiton < std::string, Country >
{
protected:
    Country ( )
    {
    }

    ~ Country ( )
    {
    }
};

// uncomment to enable lazy creation
class State : public Multiton < std::string, State/*,
MultitonDependencyLifetime < std::string, State, true >*/ >
{
private:
    // guarantee that the USA is created immediately
    // before the creation of the first state
    Country::LifetimePolicy::Dependency require_usa;

protected:
    State ( ) : require_usa ( "USA" )
    {
    }

    ~ State ( )
    {
    }
};

void f ( )
{
    // this creates the ohio instance only if lazy creation is false
    State::LifetimePolicy::Dependency require_oh ( "Ohio" );

    {
        // this creates the ohio instance if it has not been created yet
        State::Pointer ohio = State::GetInst ( "Ohio" );
        // this creates the florida instance
        State::Pointer florida = State::GetInst ( "Florida" );
    }
    int i = 5;
    // florida has been destroyed
    // but dependency on ohio is still in scope, so ohio lives on
}
// ohio is destroyed, after which point the USA is destroyed
// if it is desired for these things to live to the end of the program,
// just add static dependencies, ex:
// Country::LifetimePolicy::Dependency require_usa ( "USA" );

int main ( )
{
    f ( );
    return 0;
}


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