Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "boost/thread/once.hpp"
- #include "boost/optional.hpp"
- #include <functional>
- /// A class to encapsulate lazy initialization of an object.
- /// All instances of Lazy are thread safe and the factory
- /// is guaranteed only to be called once. However if you
- /// use this for member initialization DO NOT capture
- /// this in the lambda. See LazyMember for an alternative
- template <typename T>
- class Lazy {
- mutable boost::once_flag _once;
- mutable boost::optional<T> _data;
- typedef std::function<T()> FactoryFn;
- FactoryFn _factory;
- void Init() const { boost::call_once([&]() { _data = _factory(); }, _once); }
- public:
- Lazy(FactoryFn factory):
- _once(BOOST_ONCE_INIT),
- _factory(factory)
- {
- }
- T& Value() {
- Init();
- return *_data;
- }
- };
- Lazy<int> i([]{return 10;}); // Pretend lambda is an expensive op
- // and then some time later.
- return i.Value()
- /// A class to encapsulate lazy initialization of an object.
- /// All instances of Lazy are thread safe and the factory
- /// is guaranteed only to be called once. However if you
- /// use this for member initialization DO NOT capture
- /// this in the lambda. See LazyMember for an alternative
- template <typename T>
- class Lazy {
- mutable boost::once_flag _once;
- mutable boost::optional<T> _data;
- typedef std::function<T()> FactoryFn;
- FactoryFn _factory;
- void Init() const { boost::call_once([&]() { _data = _factory(); }, _once); }
- public:
- Lazy(FactoryFn factory):
- _factory(factory)
- {
- _once = BOOST_ONCE_INIT;
- }
- T& Value() {
- Init();
- return *_data;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement