0

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.

1 Answer 1

1

You declare your lambda to take a shared_ptr reference, but the constructor of std::thread copies all arguments by default.

If you step through the destructors being called, you'll see that it's use count is briefly 2, before the original is destroyed.

To pass the shared_ptr as a reference, you can use std::ref:

std::thread thread2([]{/*...*/}, std::ref(ptr));

This will give you the expected behavior of ptr going out of scope, which means you invoke undefined behavior when you access it anyway.

4
  • Thank you! I get my expected result. And could you explain a bit about what template magic std::ref() do? I tried std::shared_ptr<A>& ref = ptr; and pass the ref to thread2. It's also useless.
    – babel92
    Commented Nov 29, 2013 at 3:08
  • Using std::ref will cause undefined behavior, since the shared pointer is going out of scope, and using that reference would be bad.
    – Dave S
    Commented Nov 29, 2013 at 3:08
  • @DaveS Thanks for your reminding. I'm just testing out thread-safety of shared_ptr...
    – babel92
    Commented Nov 29, 2013 at 3:15
  • @melak47: std::ref doesn't interact with weak counts at all. It creates a structure which has an implicit conversion to a reference. You're still using a reference to the now-destroyed shared_ptr<A>. The fact that the memory might still be there or have sane values is irrelevant.
    – Dave S
    Commented Nov 29, 2013 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.