Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example program
- #include <iostream>
- #include <string>
- #include <cassert>
- #include <functional>
- struct TestStructure
- {
- ~TestStructure()
- {
- m_isAlive = false;
- }
- void Test() const
- {
- if (m_isAlive)
- {
- std::cout << "STRUCTURE IS ALIVE" << std::endl;
- }
- else
- {
- std::cout << "STRUCTURE HAS BEEN DEALLOCATED" << std::endl;
- }
- assert(m_isAlive);
- }
- void TestLambda()
- {
- TestStructure tester;
- m_lambda = [this, tester]()
- {
- // This releases all references to the lambda's closure
- // and deallocates it.
- m_lambda = nullptr;
- // 'tester' has now been deallocated, because it's a member of the
- // lambda's closure.
- // Less obvious problem is that the *pointer* to 'this' inside this lambda
- // is a member of the lambda's closure too and so has been also deallocated.
- // It's value is now undefined, even though the object it originally
- // pointed to still exists.
- tester.Test();
- };
- m_lambda();
- }
- bool m_isAlive = true;
- std::function<void()> m_lambda;
- };
- int main()
- {
- TestStructure tester;
- tester.TestLambda();
- return 0;
- }
Add Comment
Please, Sign In to add comment