简体   繁体   中英

shared_ptr or unique_ptr to CustomDialogEx

Hell All,

I am creating tab-controls on the fly. For this purpose, i am doing

CustomDialogEx *tabPages[TOTAL_MODULES];

and in constructor I am doing

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

and in the init() method, i am doing

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

When I tried to use the smart pointers like this

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

it is giving error at the place where I am calling the base class member functions. Example:

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

it gives the following error...

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

How do I implement using smart pointers?

Thanks.

std::unique_ptr<Type> name[Count];

So you have to change your line to:

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

Use unique_ptr if there is always one obvious owner of an object and shared_ptr if the object is hold by a group of owners using it.

If you want to know more about the backgrounds, reading this paper might help:

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

You're creating a pointer to an array of base-class objects, which isn't what you want. You want an array of pointers, as in your first example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM