智能指针和QThread问题

4

在我的代码中,有这样一段:

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);

有什么问题吗?


2
moveToThread(thread.get()) - Igor Tandetnik
3个回答

2

你需要传递一个原始指针(Qthread *)给 moveToThread。你必须使用 unique_ptr::release (thread.release()) 或 unique_ptr::get (thread.get()) 来获取原始指针,具体取决于你想实现什么功能。


但是,如果我传递原始指针,我仍然安全吗(使用智能指针的好处)? - KcFnMi
1
是的,如果您使用get(),则unique_pointer将保持其所有权(例如应在某个时刻删除托管数据)。但是release()不会这样做... @KcFnMi - HazemGomaa

2
你可以使用QScopedPointer来替代std::unique_ptr。示例

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

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

这是我使用 std::unique_ptr 和 QThread 的方式。
std::unique_ptr<QThread> top_thread{new  mythread(nullptr, &numTop, allPics[0], 1, shape, type, containEF, false)};
top_thread->start();

它运行良好

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

您可以在子类化的run成员函数中实现此std::unique_ptr<Beacon> 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->start()


很难看出你的代码片段如何适用于具体问题,因为没有解释每个参数的作用或者提问者在哪里出错了。 - user904963
1
是的,你说得对,我现在已经更清楚了。主要的问题是,在QT中有两种使用线程的方式,第一种是使用moveToThread,第二种是子类化QThread并重新实现run(),这种方式更加灵活。 - batman47steam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接