简体   繁体   中英

Are there any negative effects to using base class pointers on derived classes in c++?

I generally avoid using class pointers, since references seem way more efficient. But I have been recently forced to use them as they present the only (efficient and easy) solution to binding functions with window ids in my windows api wrapper. I have created an array of class WinControl. in my WinHandler class which handles the WndProc (Window Procedure) and add all the widgets used in the program to that array.

class WinControl   //These are not the entire classes, just the significant parts.
{
    public:
        int WinID;
        virtual void Click(void) = 0; //Pure Virtual Function.
}

class WinHandler
{ 
    WinHandler() : WCount(0) { }
    WinControl* WidgetSet[MAX_LENGTH];   // Or I can use an STL vector...
    int WCount;
    void AddWidget(Widget* w) { WCount++; WidgetSet[WCount] = w; }
}         

Then then I use:

if (WidgetSet[i]->ID == LOWORD(wParam)) WidgetSet[i]->Click();

Will this approach be alright in the long run? As the Objects actually stored in the WidgetSet will all be derivatives of class WinControl. Can anyone suggest a better approach?

NOTE: I have tried to make my question as clear as possible. If u still can't get what I am asking, please comment and I will try to elaborate the question.

What you are storing in the widget set is a pointer. NOT the object. The problem with your design is that it is not clear who is supposed to own the object thus destroy it.

I would change the interface to make ownership explicit.

Option 1:

WinHandler does NOT own the widget:

void AddWidget(Widget& w) { WCount++; WidgetSet[WCount] = &w; }

Option 2:

WinHandler Takes ownership of the widget

void AddWidget(std::auto_ptr<Widget> w) { WCount++; WidgetSet[WCount].reset(w); }
std::auto_ptr<WinControl> WidgetSet[MAX_LENGTH];

Option 2a:

(for those with newer compilers)
WinHandler Takes ownership of the widget

void AddWidget(std::unique_ptr<Widget>& w) { WCount++; WidgetSet[WCount] = std::move(w); }
std::unique_ptr<Widget> WidgetSet[MAX_LENGTH];

Option 3:

(for those with newer compilers)
WinHandler shares ownership of the widget

void AddWidget(const std::shared_ptr<Widget>& w) { WCount++; WidgetSet[WCount] = w; }
std::shared_ptr<Widget> WidgetSet[MAX_LENGTH];

The solution is OK, but watch out for memory leak: don't forget to delete everything:)

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