在下面的代码中,我希望 shared_ptr
的 use_count()
移入 std::async
成为 1
:
#include <memory>
#include <iostream>
#include <future>
using namespace std;
void fun(shared_ptr<int> sp)
{
cout << "fun: sp.use_count() == " << sp.use_count() <<
" (in gcc 4.6.3, is there a way to make this 1?)\n";
}
int main()
{
auto sp1 = make_shared<int>(5);
auto fut = async(
launch::async,
fun,
move(sp1)
);
}
我的平台使用 gcc 4.6.3,上面的代码给出了这个输出(fun: sp.use_count() == 2
):
fun: sp.use_count() == 2 (in gcc 4.6.3, is there a way to make this 1?)
关于 coliru.stacked-crooked.com ,我得到了我想要的行为(fun: sp.use_count() == 1
):
fun: sp.use_count() == 1 (in gcc 4.6.3, is there a way to make this 1?)
我不确定 coliru 使用的是什么编译器,但我猜它比 gcc 4.6.3 更新。
有没有什么方法,一些解决方法,来获得我想要的行为,而不必从 gcc 4.6.3 升级我的编译器?
最佳答案
可能的解决方法是
void fun(shared_ptr<int>* sp)
{
unique_ptr<shared_ptr<int>> guard(sp);
cout << "fun: sp.use_count() == " << sp->use_count() <<
" (in gcc 4.6.3, is there a way to make this 1?)\n";
}
int main()
{
auto sp1 = make_shared<int>(5);
auto fut = async(
launch::async,
fun,
new shared_ptr<int>(move(sp1))
);
}
也就是说,看看 gcc463 在原始代码中的何处进行了额外的复制会很有趣;似乎由 decay_copy 在 async() 中给出的临时值没有像应该的那样作为右值转发给 fun() 的参数。你不能用你的调试器介入看看发生了什么吗?
关于c++ - shared_ptr 的 use_count() 移动到 gcc 4.6.3 中的 std::async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47058099/