c++ - 在 c++11 模式下使用 QtConcurrent::run with move only 参数

标签 c++ qt c++11

我只想传递移动类型(std::unique_ptr 只是最短的例子), 实现我想在 Qt 线程池中执行的功能, 但是这样的代码会产生编译时错误:

#include <QtConcurrent>
#include <memory>

void f(std::unique_ptr<int>)
{
}

int main() {
    std::unique_ptr<int> p{new int{5}};
    QtConcurrent::run(f, std::move(p));
}

编译器提示这样的函数(Qt QtConcurrent/qtconcurrentrun.h 的一部分):

template <typename T, typename Param1, typename Arg1>
QFuture<T> run(T (*functionPointer)(Param1), const Arg1 &arg1)
{
    return (new StoredFunctorCall1<T, T (*)(Param1), Arg1>(functionPointer, arg1))->start();
}

需要std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [с _Tp = int; _Dp = std::default_delete<int>]换句话说,它使用复制而不是移动。

对于接受 Function 的其他 Qt 函数,我只使用 C++11 , 比如 QObject::connect我用 std::bind技巧:

std::bind([](const std::unique_ptr<int> &arg) {}, std::move(param));

但出于某种原因,这样的代码也无法编译:

std::unique_ptr<int> p{new int{5}};
auto func = std::bind([](std::unique_ptr<int>& a) {
        //call f here
    }, std::move(p));
QtConcurrent::run(func);

还提示 std::unique_ptr 的 delete copy constructor| .

我当然可以用 std::shared_ptr/QSharedPointer 解决它, 但可能有人建议没有额外内存分配的方法吗?

最佳答案

总而言之,不幸的是,QtConcurrent 还不支持移动语义。

主要的解决方法是做 std::auto_ptr 所做的事情:在包装器中移动拷贝。很难,但是在将移动支持添加到 Qt 并发之前没有其他方法。不过,修补起来并不是什么特别困难的事情。

关于c++ - 在 c++11 模式下使用 QtConcurrent::run with move only 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49224755/

相关文章:

qt - 复制 QTableView 的一部分

c++ - Qt 中的窗口模板(或者基本上是面向对象的 Windows)

c++ - 条件变量、互斥锁和锁的区别

multithreading - 线程,QRunnable 和 QThreadPool,我无法详细介绍

c++ - 连接函数错误QT 5

c++ - 我可以强制默认特殊成员函数为 noexcept 吗?

c++ - 当函数返回类型为 bool 时,为什么不能在 C++14 中返回共享指针?

c++ - 关于 istringstream 和 >>operator

c++ - std::uniform_int_distribution 不够随机

c++ - 在 C++ 中管理二进制数据的缓冲区