Imagine that I start a std::thread
which runs a member function of an object. What happens if that object goes out of scope in main function where I created the thread?
class ThreadClass {
public:
ThreadClass(int i) : _a(i) {
}
void foo() {
sleep(10);
std::cout << "Is it safe here? " << _a << std::endl;
}
int _a;
};
int main() {
{
ThreadClass obj(3);
std::thread t(&ThreadClass::foo, &obj);
t.detach();
}
// Here obj goes out of scope
// What about thread?
sleep(20);
return 0;
}
Would be this an undefined behavior?
No, that code isn’t safe. The thread
holds a non-owning reference to the object (via a copy of the pointer &obj
). Once the object goes out of scope, that’s a dangling reference.
Yes it is undefined behavior. More specifically, you will end up with a segmentation fault because the thread is trying to access some object which no longer exists. So here is what I'd suggest:
obj
somewhere that will not go out of scope during the lifetime of any thread(Probably global).new
and pass the pointer to the thread using std::shared_ptr
. (In this case you will have to make sure the thread calls the delete
operation, to avoid a memory leak).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With