fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. template<typename T>
  6. class lazy {
  7. //TYPES
  8. typedef typename std::aligned_storage<
  9. sizeof(T),
  10. std::alignment_of<T>::value
  11. >::type uninit_t;
  12. //MEMBERS
  13. std::function<T()> f;
  14. uninit_t value;
  15. bool cached;
  16. public:
  17. lazy(std::function<T()> f_)
  18. : f { std::move(f_) }
  19. , cached { false }
  20. { }
  21.  
  22. T& get() {
  23. if(!cached) {
  24. new(&value) T(f());
  25. cached=true;
  26. }
  27. return reinterpret_cast<T&>(value);
  28. }
  29. ~lazy() {
  30. get().~T();
  31. }
  32. };
  33.  
  34.  
  35.  
  36. std::string make_big_string() {
  37. std::cerr << "making string\n";
  38. return "hello, world";
  39. }
  40.  
  41.  
  42. int main() {
  43. lazy<std::string> l_str(make_big_string);
  44. std::cerr << "get1\n";
  45. std::cout << l_str.get() << '\n';
  46. std::cerr << "get1\n";
  47. std::cout << l_str.get() << '\n';
  48. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
hello, world
hello, world