jeudi 29 mars 2018

Different behaviour while passing shared_ptr to weak_ptr in thread functions and normal functions

I'm having a thread function which takes a weak_ptr<> and I pass my shared_ptr<> in the thread function.

Legally weak_ptr<> should not increment the reference count of shared_ptr<>, however, unless I typecast with weak_ptr<> while passing the same to the thread function, it increments the reference count (unexpected)

This behaviour happens only with thread functions and not with normal function calls.

Here is the code for thread function

void thrdfn(weak_ptr<int> wp) {
    cout<<wp.use_count()<<endl;  // Prints 2
}

int main() {
    shared_ptr<int> sp = make_shared<int>();
    thread th { thrdfn, (sp)};
    th.join();
    return 0;
}

However, when I typecast while creating thread, it behaves properly

void thrdfn(weak_ptr<int> wp) {
    cout<<wp.use_count()<<endl;  // Prints 1
}

int main() {
    thread th { thrdfn, weak_ptr<int>(sp)}; // typecast 
}

When I call the function as a normal function call, it works fine without typecasting

void thrdfn(weak_ptr<int> wp) {
    cout<<wp.use_count()<<endl;  // Prints 1
}

int main() {
    shared_ptr<int> sp = make_shared<int>();
    thrdfn(sp);
    return 0;
}

Behaviour is same with multiple compilers

Aucun commentaire:

Enregistrer un commentaire