Suppose I have a class that can run some code asynchronously, and that asynchronous code uses this instance of the class to perform functions such as member functions, reading data elements, etc. Obviously, the class instance must survive the background thread, access to them is safe. Is it enough to ensure this by attaching a background thread in the destructor? For example:
#include <iostream>
#include <thread>
class foo final
{
public:
foo() = default;
void bar() {
std::cout << "Hopefully there nothing wrong with using " << this << "\n";
}
void bar_async() {
if (!m_thread.joinable()) {
m_thread = std::thread{&foo::bar, this};
}
}
~foo() {
if (m_thread.joinable()) {
std::cout << "Waiting for " << m_thread.get_id() << "\n";
m_thread.join();
}
}
private:
std::thread m_thread;
};
int main() {
foo f;
f.bar_async();
}
In particular, I am concerned about the rules of life of the object :
For any class object whose destructor is not trivial, the lifetime expires when the execution of the destructor begins.
... , , , glvalue, , undefined:...
, this->bar() ~foo() undefined, "" .