2014-12-02 95 views
0

地獄所有,shared_ptr或unique_ptr到CustomDialogEx

我在飛行中創建標籤控件。爲此,我在做什麼

CustomDialogEx *tabPages[TOTAL_MODULES]; 

,並在構造函數中我做

CModuleTabCtrl::CModuleTabCtrl() 
{  
    tabPages[0] = new CPodule; 
    tabPages[1] = new CSBModule; 
    tabPages[2] = new CPTModule; 
    tabPages[3] = new CQSModule; 
} 

,並在init()方法,我在做什麼

void CModuleTabCtrl::Init() 
{ 
    // Add Dialog pages to tabPages array. 
    tabPages[0]->Create(IDD_DLG_P, this); 
    tabPages[1]->Create(IDD_DLG_SB, this); 
    tabPages[2]->Create(IDD_DLG_PT, this); 
    tabPages[3]->Create(IDD_DLG_QS, this); 
} 

當我試圖用像這樣的智能指針

std::unique_ptr<CustomDialogEx[TOTAL_MODULES]>tabPages; 

它在我調用基類成員函數的地方給出錯誤。 例子:

tabPages[0]->Create(IDD_DLG_P, this); 

它提供了以下錯誤......

left of '->Create' must point to class/struct/union/generic type 

如何實現用智能指針?

謝謝。

回答

1

您正在創建一個指向基類對象數組的指針,這不是您想要的。你想要一個指針數組,如你的第一個例子:

std::unique_ptr<CustomDialogEx> tabPages[TOTAL_MODULES]; 
tabPages[0].reset(new CPodule);  // Create the first object 
tabPages[0]->Create(IDD_DLG_P, this); // Do the weird second-stage initialisation 
2
std::unique_ptr<Type> name[Count]; 

所以,你有你的行更改爲:

std::unique_ptr<CustomDialogEx> tabPages[TOTAL_MODULES]; 

使用的unique_ptr如果總是存在的一個明顯的所有者對象和 shared_ptr如果該對象由一組所有者持有使用它。

如果您想了解更多有關的背景,閱讀本文可能會有所幫助:

http://www.umich.edu/~eecs381/handouts/C++11_smart_ptrs.pdf

相關問題