I have this piece of code:
class A
{
public:
A()
{
std::cout << "ctor called\n";
}
~A()
{
std::cout << "dtor called\n";
}
};
int main()
{
std::thread thread1([]{
std::shared_ptr<A> ptr(new A);
std::thread thread2([](std::shared_ptr<A>& arg){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "use_count: " << arg.use_count() << std::endl;
},ptr);
thread2.detach();
std::cout << "thread1 quitting\n";
});
thread1.detach();
while (1);
return 0;
}
And got this result:
ctor called
thread1 quitting
use_count: 1
dtor called
However, I expected this to happen:
ctor called
thread1 quitting
dtor called
use_count: 0
Because I think passing the shared_ptr by reference won't increase its ref count, thus the managed object will be destroyed as soon as thread1 gets out of scope. Could you tell me why I'm wrong? Thanks.