I've been trying to do something similar to the following (the following is provided to demonstrate the compilation error so if you wanted to compile it you could, nothing more)
//main.cpp
#include <QApplication>
#include "test.h"
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
Test t;
std::string s = "hi ";
std::unique_ptr<std::string> sptr = std::make_unique<std::string>(s);
t.foo(sptr);
return a.exec();
}
test.h
//test.h
#ifndef TEST_H
#define TEST_H
#include <QObject>
#include <QThread>
#include <string>
#include <QApplication>
#include <memory>
class Test : public QObject{
Q_OBJECT
public:
void foo(std::unique_ptr<std::string> t_ptr);
void bar(std::unique_ptr<std::string> t_ptr);
};
#endif //TEST_H
test.cpp
//test.cpp
#include "test.h"
#include <iostream>
void Test::foo(std::unique_ptr<std::string> t_ptr){
QThread * thread = new QThread(this);
moveToThread(thread);
auto lambda = [=, uptr = std::move(t_ptr) ]()mutable{bar(uptr);};
connect(thread, &QThread::started, lambda);
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
thread->start();
}
void Test::bar(std::unique_ptr<std::string> t_ptr){
t_ptr->append("hello");
std::cout << *t_ptr << std::endl;
moveToThread(QApplication::instance()->thread());
}
But I can't seem to compile no matter what I do, I end up with either just this:
error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string<char>; _Dp = std::default_delete<std::__cxx11::basic_string<char> >]'
auto lambda = [=, uptr = std::move(t_ptr) ]()mutable{bar(uptr);};
^
note: declared here
unique_ptr(const unique_ptr&) = delete;
or in addition to that error, this one as well:
In member function 'void Test::foo(std::unique_ptr<T>)':
error: use of deleted function 'Test::foo(std::unique_ptr<std::__cxx11::basic_string<char> >)::<lambda()>::<lambda>(const Test::foo(std::unique_ptr<std::__cxx11::basic_string<char> >)::<lambda()>&)'
connect(thread, &QThread::started, lambda);
Changing to mutable results in the same error as well, and obviously I've already imployed the answer found here.
I'm sure it has to do with the fact that the lambda capture makes the unique_ptr
const, but then i'm not sure what to do to actually accomplish what I want sans actually making the unique_ptr
a member variable.
EDIT:
Ok, I tried these things before any one else commented, and they also didn't work, but because I'm getting responses about "try this" I'm going to show you some other permutations that don't work:
Using std::move(uptr) (same error)
Lambda creation in connect
connect(thread, &QThread::started, [=, uptr = std::move(sensor_ptr) ]()mutable{bar(uptr);};);
same error.
Changing bar
to take rvalue, same error
Changing bar
to take const value, same error
Changing bar
to take const rvalue, same error