【发布时间】:2018-09-08 14:52:53
【问题描述】:
我有一个线程函数,它需要一个weak_ptr,我在线程函数中传递了我的shared_ptr。
从法律上讲,weak_ptr 不应增加 shared_ptr 的引用计数,但是,除非我在将其传递给线程函数时使用 weak_ptr 进行类型转换,否则它会增加引用计数(意外)
这种行为只发生在线程函数中,而不是普通函数调用。
这是线程函数的代码
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;
}
但是,当我在创建线程时进行类型转换时,它的行为正常
void thrdfn(weak_ptr<int> wp) {
cout<<wp.use_count()<<endl; // Prints 1
}
int main() {
thread th { thrdfn, weak_ptr<int>(sp)}; // typecast
}
当我将函数作为普通函数调用时,它可以正常工作而无需类型转换
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;
}
多个编译器的行为相同
【问题讨论】:
标签: c++ multithreading c++11 c++14 smart-pointers