【问题标题】:smart pointer and QThread issue智能指针和 QThread 问题
【发布时间】:2017-03-12 13:17:37
【问题描述】:

在我的代码中的某个时刻,我有:

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

前几天我读到了一个叫做智能指针的东西。如果我理解,它可能适合上面的代码,我试过了:

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

这导致:

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

怎么了?

【问题讨论】:

  • moveToThread(thread.get())

标签: c++ multithreading c++11 qt5 c++14


【解决方案1】:

您需要将原始指针 (Qthread *) 传递给 moveToThread。您必须使用 unique_ptr::release (thread.release()) 或 unique_ptr::get (thread.get()) 来获取原始指针,具体取决于您要实现的目标。

【讨论】:

  • 但是传递原始指针我仍然安全吗(利用智能指针的好处)?
  • 是的,如果您使用 get(),您的 unique_pointer 将保持其所有权 a(例如,应该在某个时候删除托管数据)。 release() 并没有这样做...... @KcFnMi
【解决方案2】:

在我的项目中,我是这样使用qthread的

另一种让代码在单独的线程中运行的方法是子类化 QThread 并重新实现 run()

这是我对std::unique_ptrQthread的使用

std::unique_ptr<QThread> top_thread{new  mythread(nullptr, &numTop, allPics[0], 1, shape, type, containEF, false)};
top_thread->start();

效果很好

在你的情况下,你可以这样做

您可以在子类run 成员函数中实现这个std::unique_ptr&lt;Beacon&gt; beacon {new Beacon(beg, end)};。然后只需使用 thread->start()

class thread:public QThread
{
    Q_OBJECT
public:
    thread(QObject *parent = nullptr);
    ~thread();
    virtual void run();

public:
    

};

run()

void mythread::run() {
    std::unique_ptr<Beacon> beacon {new Beacon(beg, end)};
}

那么你可以简单地使用thread-&gt;start()

【讨论】:

  • 很难看出您的代码 sn-p 如何适用于特定问题,因为没有解释每个参数的作用或提出问题的人哪里出错了。
  • 是的,你说得对,我现在说得更清楚了,主要是因为QT中有两种使用线程的方法,第一种是他使用moveToThread,第二种是子类QThread和重新实现run(),更灵活
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多