Search code examples
c++multithreadingc++11qt5c++14

smart pointer and QThread issue


At some point in my code I have:

QThread* thread = new QThread;
Beacon *beacon = new Beacon(beg, end);
beacon->moveToThread(thread);

And the other day I was reading about this thing called smart pointer. If I understand, it might fit in the peace of code above, I tried:

std::unique_ptr<QThread> thread {new QThread};
std::unique_ptr<Beacon> beacon {new Beacon(beg, end)};
beacon->moveToThread(thread);

This, led to:

error: no viable conversion from 'std::unique_ptr<QThread>' to 'QThread *'
    beacon->moveToThread(thread);

What's wrong?


Solution

  • You need to pass a raw pointer (Qthread *) to moveToThread. You have to use either unique_ptr::release (thread.release()) or unique_ptr::get (thread.get()) to get the raw pointer, depending on what you are trying to achieve.