c++ - shared_ptr 的 use_count() 移动到 gcc 4.6.3 中的 std::async

标签 c++ c++11 shared-ptr stdasync std-future

在下面的代码中,我希望 shared_ptruse_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/

相关文章:

c++ - 如何在可变参数包中找到 "min"类型?

c++ - MFC 在对象之间发送信号

c++ - 如何确定存储在数组中的项目数?

c++ - 如何正确地从 shared_ptr 移动/读取

c++ - 前/后增量的左值和右值

c++ - 迭代器两个**的含义

c++ - 我目前正在使用什么 c++ norme?

c++ - unique_ptr 和多态性

c++ - 如何传递对 std::shared_ptr 管理的指针的引用

C++ 在 boost::ptr_container 中共享元素?