开发者

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

开发者 https://www.devze.com 2023-03-21 01:32 出处:网络
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 functio

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 su开发者_如何转开发ggest 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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消