Qt Documentation states that QtConcurrent::run
can be used to run a member function in another thread by passing the pointer to the object as the first argument. However, I couldn't find any info if smart pointers can be used in this case. Specifically, I wanted to use it with std::shared_ptr
.
It should be impossible to pass a smart pointer to QtConcurrent::run since there is no matching overload available.
I would suggest a solution using lambdas:
std::shared_ptr<Obj> obj_ptr(new Obj());
QtConcurrent::run([obj_ptr](){ obj_ptr->func(); });
Due to the internal reference counter of shared_ptr you don't have to worry about the life time of the object owned by the smart pointer since you capture a copy in the lambda function.
Another solution would be to pass the raw pointer:
std::shared_ptr<Obj> obj_ptr(new Obj());
QtConcurrent::run(obj_ptr.get(), &Obj::func);
But this is quite risky since you have to worry about the life time of your object.
In the end, I would prefer the first method since it is much safer.