Guest User

Untitled

a guest
Jan 18th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. // Example program
  2. #include <iostream>
  3. #include <string>
  4. #include <cassert>
  5. #include <functional>
  6.  
  7. struct TestStructure
  8. {
  9. ~TestStructure()
  10. {
  11. m_isAlive = false;
  12. }
  13.  
  14. void Test() const
  15. {
  16. if (m_isAlive)
  17. {
  18. std::cout << "STRUCTURE IS ALIVE" << std::endl;
  19. }
  20. else
  21. {
  22. std::cout << "STRUCTURE HAS BEEN DEALLOCATED" << std::endl;
  23. }
  24. assert(m_isAlive);
  25. }
  26.  
  27. void TestLambda()
  28. {
  29. TestStructure tester;
  30.  
  31. m_lambda = [this, tester]()
  32. {
  33. // This releases all references to the lambda's closure
  34. // and deallocates it.
  35. m_lambda = nullptr;
  36. // 'tester' has now been deallocated, because it's a member of the
  37. // lambda's closure.
  38. // Less obvious problem is that the *pointer* to 'this' inside this lambda
  39. // is a member of the lambda's closure too and so has been also deallocated.
  40. // It's value is now undefined, even though the object it originally
  41. // pointed to still exists.
  42. tester.Test();
  43. };
  44.  
  45. m_lambda();
  46. }
  47.  
  48. bool m_isAlive = true;
  49. std::function<void()> m_lambda;
  50. };
  51.  
  52. int main()
  53. {
  54. TestStructure tester;
  55. tester.TestLambda();
  56. return 0;
  57. }
Add Comment
Please, Sign In to add comment