Monday, February 13, 2012

Constructing static class members on-demand

A little pattern I like to use when I have resources shared among all instances of a class which should only be constructed when an object of the class is instantiated (and destroyed with the last object):

class Foo
{
private:
    struct SharedProperties
    {
        std::unique_ptr baz;
    };
    static std::weak_ptr<SharedProperties> m_weakShared;
    std::shared_ptr<SharedProperties> m_shared;
};

Foo::Foo()
{
    if (!m_weakShared.expired())
    {
        m_shared = m_weakShared.lock();
    }
    else
    {
        m_shared = std::make_shared<SharedProperties>();
        m_weakShared = std::weak_ptr<SharedProperties>(m_shared);

        // Initialize the shared properties here
        m_shared->baz.reset(new Baz());
    }
}

No comments:

Post a Comment