无法传递std :: vector <std :: unique_ptr <>&gt;到std :: thread </std :: unique_ptr <>

时间:2015-01-18 15:29:48

标签: multithreading c++11 unique-ptr

我创建了一个 threadpool ,它将函数和参数捕获到元组中,然后在任务出列时完美转发。

但是我无法通过rvalue将unique_ptr的向量传递给线程。简化项目如下:

#include <future>
#include <memory>
#include <vector>

template <typename F, typename... Args>
typename std::result_of<F(Args...)>::type pushTask(F&& f, Args&&... args)
{
    using result_type = typename std::result_of<F(Args...)>::type;

    // create a functional object of the passed function with the signature std::function<result_type(void)> by creating a
    // bound Functor lambda which will bind the arguments to the function call through perfect forwarding and lambda capture
    auto boundFunctor = [func = std::move(std::forward<F>(f)),
                         argsTuple = std::move(std::make_tuple(std::forward<Args>(args)...))](void) mutable->result_type
    {
        // forward function and turn variadic arguments into a tuple
        return result_type();
    };

    // create a packaged task of the function object
    std::packaged_task<result_type(void)> taskFunctor{ std::move(boundFunctor) };
}

 int main(int argc, char *argv [])
 {
     auto testvup = [](std::vector<std::unique_ptr<int>>&& vup)
    {

    };
    std::vector<std::unique_ptr<int>> vup;
    pushTask(testvup, std::move(vup));
}

我在VS2015中遇到以下编译错误,而不是使用std :: function或std :: packaged_task

严重性描述项目文件行

Error   error C2280: 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function Stack   xmemory0    659

通过包含std::vector的右值传递其他参数。

是否有其他人遇到过此或有建议。

1 个答案:

答案 0 :(得分:2)

C ++标准部分§20.9.11.2.1[func.wrap.func]

  

template<class F> function(F f);

     

template <class F, class A> function(allocator_arg_t, const A& a, F f);

     

要求:F应为 CopyConstructible 。 f应该可以调用   参数类型ArgTypes和返回类型R.复制构造函数和   A的析构函数不会抛出异常。

您的lambda函数boundFunctor是一种仅移动类型(因为它只捕获移动类型,因为std::unique_ptr无法复制)

因此,boundFunctor不可复制,不适合作为std::function的参数

相关问题