2016-10-30 46 views
0

在我的代碼中的一些問題,我有:智能指針和QThread的問題

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

有什麼不對?

+1

'moveToThread(thread.get())' –

回答

1

您需要將原始指針(Qthread *)傳遞給moveToThread。您必須使用unique_ptr::releasethread.release())或unique_ptr::getthread.get())以獲取原始指針,具體取決於您嘗試實現的目標。

+0

但是傳遞原始指針我仍然安全(使用智能指針的好處)? – KcFnMi

+1

是的,如果你使用get(),你的unique_pointer會保持它的所有權(例如,應該在某個時候刪除被管理的數據)。 release()不會那樣做,儘管... @KcFnMi – HazemGomaa