fork download
  1. #include <functional>
  2. #include <iostream>
  3.  
  4. struct FData
  5. {
  6. int id = 1;
  7. int x = 5;
  8. };
  9.  
  10. std::function<void()> test(const FData& in)
  11. {
  12. return [copy = in]()
  13. {
  14. std::cout << "addr=" << &copy << " id=" << copy.id << " x=" << copy.x << std::endl;
  15. };
  16. }
  17.  
  18. int main()
  19. {
  20. std::function<void()> callback;
  21.  
  22. {//scoped to destroy obj1
  23. FData obj1;
  24.  
  25. std::cout << "addr=" << &obj1 << " id=" << obj1.id << " x=" << obj1.x << std::endl;
  26.  
  27. callback = test(obj1);
  28. }
  29.  
  30. {
  31. FData obj2;
  32. //attempt to overwrite obj1 memory
  33. obj2.id = 2;
  34. obj2.x = 7;
  35.  
  36. std::cout << "addr=" << &obj2 << " id=" << obj2.id << " x=" << obj2.x << std::endl;
  37.  
  38. callback();
  39. }
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
addr=0x7ffe538c1ee8 id=1 x=5
addr=0x7ffe538c1ee8 id=2 x=7
addr=0x7ffe538c1ef0 id=1 x=5