If the shared_ptr is destroyed, what happens to "this" if captured in a lambda to be run on a thread? Shouldn't it have thrown an exception in the below case since the object Test was destroyed before the thread could finish running.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds
class Test
{
private:
int testInt = 0;
public:
std::thread TestMethod()
{
auto functor =
[this]() ->void
{
sleep_until(system_clock::now() + seconds(1));
++testInt; cout<<testInt<<endl;
};
std::thread t1(functor);
testInt = 6;
return t1;
}
~Test()
{
cout<<"Destroyed\n";
testInt = 2;
}
};
int main()
{
cout<<"Create Test\n";
auto testPtr = std::make_shared<Test>();
auto t = testPtr->TestMethod();
testPtr = nullptr;
cout<<"Destroy Test\n";
t.join();
return 0;
}
Output is
Create Test
Destroyed
Destroy Test
3
How is the lambda able to access testInt of a destroyed object ?