I'm trying to see what happens when an object is destroyed during thread execution.
While thread_
executes f
, X
is destroyed.
Can someone explain why End
is displayed and the program doesn't stop with a segfault?
execute-1
f-1
f-2
DestrX
End
#include <iostream>
#include <thread>
using namespace std;
struct X
{
void execute()
{
std::cout<<"execute-1\n";
}
void f()
{
std::cout<<"f-1\n";
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout<<"f-2\n";
}
~X()
{
std::cout<<"DestrX\n";
}
};
int main()
{
std::thread thread_;
std::shared_ptr<X> x = std::make_shared<X>();
thread_ = std::thread(
[&]()
{
x->f();
});
x->execute();
x.reset();
thread_.join();
std::cout<<"End\n";
return 0;
}