首页 > 解决方案 > 尝试将参数传递给方法时出现“调用隐式删除的复制构造函数”错误

问题描述

我正在尝试为我的应用程序使用 CPTL 线程池。

所以,我有一个具有这个定义的函数:

static void Invoke( int id, std::unique_ptr<BaseService> svc );

并尝试将其传递给 CPTL“推送”方法以在线程池中排队:

pThreadPool->push( std::ref(App::Invoke), std::move( svc ) );

但我收到了这个错误:

/home/hadi/CLionProjects/App/App.cpp:211:27: error: no matching member function for call to 'push'
    pThreadPool->push( std::ref(App::Invoke), std::move( svc ) );
    ~~~~~~~~~~~~~^~~~
/home/hadi/CLionProjects/App/include/cptl/ctpl.h:152:14: note: candidate template ignored: substitution failure [with F = std::__1::reference_wrapper<void (int, std::__1::unique_ptr<BaseService, std::__1::default_delete<BaseService> >)>, Rest = <std::__1::unique_ptr<BaseService, std::__1::default_delete<BaseService> >>]: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<BaseService, std::__1::default_delete<BaseService> >'
        auto push(F && f, Rest&&... rest) ->std::future<decltype(f(0, rest...))> {
             ^                                                        ~~~~
/home/hadi/CLionProjects/App/include/cptl/ctpl.h:171:14: note: candidate function template not viable: requires single argument 'f', but 2 arguments were provided
        auto push(F && f) ->std::future<decltype(f(0))> {
             ^
1 error generated.

谁能告诉我如何解决这个问题?谢谢。

标签: c++c++11

解决方案


似乎 CPTL 在第152 行有一个错误,或者不支持仅移动参数(找不到任何文档,因此无法确定):

    auto push(F && f, Rest&&... rest) ->std::future<decltype(f(0, rest...))> {

即使在调用中使用,它也在 SFINAE 中使用push,该 SFINAE 失败并从可行候选者列表中排除过载。std::forward<Rest>(rest)...rest...

通常打包任务的参数存储在队列中,因此需要可复制。这排除了使用,unique_ptr因为它不可复制(它是独一无二的!)。

作为一种解决方法,您可以使用shared_ptr或者,如果 的生命周期svc超过线程池的生命周期,则使用原始指针。


推荐阅读