Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. #include "boost/thread/once.hpp"
  2. #include "boost/optional.hpp"
  3. #include <functional>
  4. /// A class to encapsulate lazy initialization of an object.
  5. /// All instances of Lazy are thread safe and the factory
  6. /// is guaranteed only to be called once. However if you
  7. /// use this for member initialization DO NOT capture
  8. /// this in the lambda. See LazyMember for an alternative
  9. template <typename T>
  10. class Lazy {
  11. mutable boost::once_flag _once;
  12. mutable boost::optional<T> _data;
  13. typedef std::function<T()> FactoryFn;
  14. FactoryFn _factory;
  15. void Init() const { boost::call_once([&]() { _data = _factory(); }, _once); }
  16. public:
  17. Lazy(FactoryFn factory):
  18. _once(BOOST_ONCE_INIT),
  19. _factory(factory)
  20. {
  21.  
  22. }
  23.  
  24. T& Value() {
  25. Init();
  26. return *_data;
  27. }
  28. };
  29.  
  30. Lazy<int> i([]{return 10;}); // Pretend lambda is an expensive op
  31. // and then some time later.
  32. return i.Value()
  33.  
  34. /// A class to encapsulate lazy initialization of an object.
  35. /// All instances of Lazy are thread safe and the factory
  36. /// is guaranteed only to be called once. However if you
  37. /// use this for member initialization DO NOT capture
  38. /// this in the lambda. See LazyMember for an alternative
  39. template <typename T>
  40. class Lazy {
  41. mutable boost::once_flag _once;
  42. mutable boost::optional<T> _data;
  43. typedef std::function<T()> FactoryFn;
  44. FactoryFn _factory;
  45. void Init() const { boost::call_once([&]() { _data = _factory(); }, _once); }
  46. public:
  47. Lazy(FactoryFn factory):
  48. _factory(factory)
  49. {
  50. _once = BOOST_ONCE_INIT;
  51. }
  52.  
  53. T& Value() {
  54. Init();
  55. return *_data;
  56. }
  57.  
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement