A thread is created with a member function, but the related object reaches the end of scope and distroyed. I found it strange that the thread continues without error. I guess it's pure luck, but I cannot prove it.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
using namespace std;
struct Base {
int N = 10;
Base(int _N) : N(_N) {
cout << "Base Ctor\n";
}
virtual ~Base(){
cout << "Base Dtor\n";
}
void counter() {
for ( auto i{0}; i < N; ++i ) {
this_thread::sleep_for( 1s );
cout << "step: " << i << " / " << N << endl;
}
}
};
int main() {
{
// limit the scope of b
Base b(10);
thread th( &Base::counter, std::ref(b) );
th.detach();
std::this_thread::sleep_for( 5s );
// destruct b
}
std::this_thread::sleep_for( 10s );
return 0;
}
I got the following result:
Base Ctor
step: 0 / 10
step: 1 / 10
step: 2 / 10
step: 3 / 10
Base Dtor
step: 4 / 10
step: 5 / 10
step: 6 / 10
step: 7 / 10
step: 8 / 10
step: 9 / 10