I know that std::thread
destructors are called on main exit, or when a thread object goes out of scope.
But is it also destroyed when a function that it is calling is done executing?
If not what happens to such a thread, can I still join()
it?
Destructors are called when one of the following events occurs: A local (automatic) object with block scope goes out of scope. An object allocated using the new operator is explicitly deallocated using delete . The lifetime of a temporary object ends.
No. You never need to explicitly call a destructor (except with placement new ). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.
While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.
No, most destructors are not run on exit() . Essentially, when exit is called static objects are destroyed, atexit handlers are executed, open C streams are flushed and closed, and files created by tmpfile are removed.
But is it also destroyed when a function that it is calling is done executing? If not what happens to such a thread, can I still
join()
it?
No it isn't destroyed, but marked joinable()
. So yes you can still join()
it.
Otherwise as from the title of your question ("When is std::thread destructor called?") and what you say in your post
I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.
It's like with any other instance: The destructor is called when the instance goes out of scope or delete
is called in case the instances were allocated dynamically.
Here's a small example code
#include <thread>
#include <iostream>
#include <chrono>
using namespace std::chrono_literals;
void foo() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(foo);
std::this_thread::sleep_for(1s);
std::cout << "t.joinable() is " << t.joinable() << std::endl;
t.join();
}
The output is
Hello from thread! t.joinable() is 1
See it live.
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