std::thread and class constructor and destructor
Posted
by
toeplitz
on Stack Overflow
See other posts from Stack Overflow
or by toeplitz
Published on 2012-10-19T22:57:13Z
Indexed on
2012/10/19
23:00 UTC
Read the original article
Hit count: 144
When testing threads in C++11 I have created the following example:
#include <iostream>
#include <thread>
class Foo {
public:
Foo(void) {
std::cout << "Constructor called: " << this << std::endl;
}
~Foo(void) {
std::cout << "Destructor called: " << this << std::endl;
}
void operator()() const {
std::cout << "Operatior called: " << this << std::endl;
}
};
void test_normal(void) {
std::cout << "====> Standard example:" << std::endl;
Foo f;
}
void test_thread(void) {
std::cout << "====> Thread example:" << std::endl;
Foo f;
std::thread t(f);
t.detach();
}
int main(int argc, char **argv)
{
test_normal();
test_thread();
for(;;);
}
Which prints the following:
Why is the destructor called 6 times for the thread? And why does the thread report different memory locations?
© Stack Overflow or respective owner