簡體   English   中英

shared_ptr或unique_ptr到CustomDialogEx

[英]shared_ptr or unique_ptr to 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

如何使用智能指針實現?

謝謝。

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM