fork download
  1. #include <iostream>
  2. #include <mutex>
  3.  
  4. class Foo
  5. {
  6. public:
  7. Foo() : _i(NULL) {}
  8. int get()
  9. {
  10. std::call_once(_flag,
  11. [&]()
  12. {
  13. std::cout << "Setting _i\n";
  14. _i = new int(5);
  15. });
  16. return *_i;
  17. }
  18. Foo(const Foo&) = delete;
  19. Foo& operator=(const Foo&) = delete;
  20. private:
  21. std::once_flag _flag;
  22. int* _i;
  23. };
  24.  
  25. int main()
  26. {
  27. Foo f;
  28.  
  29. std::cout << f.get() << "\n";
  30. std::cout << f.get() << "\n";
  31. std::cout << f.get() << "\n";
  32. std::cout << f.get() << "\n";
  33. std::cout << f.get() << "\n";
  34. std::cout << f.get() << "\n";
  35. std::cout << f.get() << "\n";
  36. std::cout << f.get() << "\n";
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 3060KB
stdin
Standard input is empty
stdout
Setting _i
5
5
5
5
5
5
5
5