本文介绍了在线程函数和普通函数中将 shared_ptr 传递给 weak_ptr 时的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 限时删除!! 我有一个线程函数,它需要一个 weak_ptr 并且我在线程函数中传递了我的 shared_ptr.I'm having a thread function which takes a weak_ptr<> and I pass my shared_ptr<> in the thread function.从法律上讲,weak_ptr 不应该增加 shared_ptr 的引用计数,但是,除非我使用 weak_ptr 进行类型转换,同时将其传递给线程函数,否则它会增加引用计数(意外)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.这是线程函数的代码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 properlyvoid 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 typecastingvoid 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;}行为与多个编译器相同推荐答案当你写构造一个 std::thread(我去掉了多余的括号):When you write construct a std::thread (and I removed the superfluous parentheses):thread th{thrdfn, sp};会发生什么:新的执行线程开始执行std::invoke(decay_copy(std::forward<Function>(f)), decay_copy(std::forward<Args>(args))...);其中decay_copy 定义为where decay_copy is defined astemplate <class T>std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }也就是说,您的 shared_ptr 被复制到线程中,然后您从该副本中取出 weak_ptr.所以有两个 shared_ptr:你的和 thread 的.Which is to say, your shared_ptr is copied into the thread and you take a weak_ptr off of that copy. So there are two shared_ptrs: yours and the thread's. 这篇关于在线程函数和普通函数中将 shared_ptr 传递给 weak_ptr 时的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-06 09:42