fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <array>
  4. #include <cassert>
  5. #include <cstdlib>
  6. using namespace std;
  7.  
  8. template<typename T>
  9. class lazy {
  10. using init_func_t = function<T()>;
  11. mutable T value;
  12. mutable init_func_t init;
  13. public:
  14. lazy(init_func_t func): init(func){
  15. assert(init);
  16. }
  17.  
  18. lazy(const T &v): value(v){}
  19.  
  20. lazy(const lazy &other){
  21. lazy(other.init.target());
  22. }
  23.  
  24.  
  25. operator T() const{
  26. if(init){
  27. value = init();
  28. init = init_func_t();
  29. }
  30. return value;
  31. }
  32.  
  33. lazy<T> &operator=(const lazy<T> &other){
  34. if(other.init){
  35. init = init_func_t(other.init.target());
  36. }
  37. else{
  38. init = init_func_t();
  39. value = other;
  40. }
  41. return *this;
  42. }
  43. };
  44.  
  45. struct car{
  46. static constexpr size_t str_buff_size = 64;
  47. lazy<char *> model { []{return new char[str_buff_size];} };
  48. };
  49.  
  50. int main(){
  51. array<car, 5> cars;
  52. for(auto &car: cars){
  53. fgets(car.model, car::str_buff_size, stdin);
  54. printf(car.model);
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 3464KB
stdin
mazda
toyota
opel
audi
bmw
stdout
mazda
toyota
opel
audi
bmw