为什么不能在 QFuture 中使用 unique_ptr?
这是我的示例代码,我使用 std::vector
作为未来的结果。
#include "mainwindow.h"
#include <QLineEdit>
#include <QtConcurrent/QtConcurrent>
#include <vector>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent) {
auto model = new QLineEdit(this);
this->setCentralWidget(model);
auto watcher = new QFutureWatcher<std::vector<std::unique_ptr<std::string>>>(/*this*/);
auto future = QtConcurrent::run([this]() -> std::vector<std::unique_ptr<std::string>> {
std::vector<std::unique_ptr<std::string>> res;
for (int k = 0; k < 100; ++k) {
auto str = std::make_unique<std::string>("Hi");
res.push_back(std::move(str));
}
return res;
});
connect(watcher, &QFutureWatcher<std::vector<std::unique_ptr<std::string>>>::finished, this, [=]() {
for (const auto &item : future.result()){
model->setText(model->text() + QString::fromStdString(*item));
}
delete watcher;
});
watcher->setFuture(future);
}
MainWindow::~MainWindow() {
}
但这段代码无法编译。 这是日志,
/Users/ii/QT/qt-everywhere-src-6.2.0-beta4/include/QtCore/qfuture.h:328:12: note: in instantiation of member function 'std::vector<std::unique_ptr<std::string>>::vector' requested here
return d.resultReference(0);
^
/Users/ii/CLionProjects/simpleQT/mainwindow.cpp:22:40: note: in instantiation of function template specialization 'QFuture<std::vector<std::unique_ptr<std::string>>>::result<std::vector<std::unique_ptr<std::string>>, void>' requested here
for (const auto &item : future.result()){
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk/usr/include/c++/v1/__memory/base.h:103:16: note: candidate template ignored: substitution failure [with _Tp = std::unique_ptr<std::string>, _Args = <std::unique_ptr<std::string> &>]: call to implicitly-deleted copy constructor of 'std::unique_ptr<std::string>'
constexpr _Tp* construct_at(_Tp* __location, _Args&& ...__args) {
^
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 takeResult 而不是
result
为了使用仅移动类型。QFuture
的设计并没有真正考虑到可移动类型,您最好使用可复制类型或std::future
来代替。You need to use takeResult instead of
result
in order to use move only types.QFuture
isn't really designed with movable types in mind and you might be better off using a copyable type orstd::future
instead.