【发布时间】:2015-01-18 15:29:48
【问题描述】:
我创建了一个线程池,它将函数和参数捕获到元组中,然后在任务出队时完美转发。
但是我无法通过右值将 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 有效。
有没有其他人遇到过这个问题或有建议。
【问题讨论】:
-
std::function执行类型擦除。它是可复制的,因此它需要您存储在其中的函数对象的可复制性。 -
是的,我选择的 std::function 就是一个糟糕的例子。但是,我得到与 std::packaged_task 相同的错误,它应该采取移动可构造对象
标签: multithreading c++11 unique-ptr