在c++中对派生类使用基类指针有什么负面影响吗?

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

本文关键字:什么 影响 指针 基类 c++ 派生      更新时间:2023-10-16

我通常避免使用类指针,因为引用似乎更有效。但我最近被迫使用它们,因为它们是在我的windows api包装器中绑定带有窗口id的函数的唯一(有效且简单)解决方案。我已经创建了一个类WinControl数组。在我的WinHandler类中,它处理WndProc(窗口过程),并将程序中使用的所有小部件添加到该数组中。

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

然后我使用:

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

从长远来看,这种方法是否可行?因为实际存储在WidgetSet中的对象都是类WinControl的派生。有人能提出更好的方法吗?

注意:我已经尽量把我的问题说清楚了。如果你仍然不明白我的问题,请评论,我会尽量详细说明这个问题。

在小部件集中存储的是一个指针。不是对象。你的设计的问题是,它不清楚谁应该拥有对象,因此销毁它。

我将改变接口使所有权明确。

选项1:

WinHandler does NOT拥有小部件:

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

选项2:

WinHandler 获取部件的所有权

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

选项2:

(对于使用较新编译器的用户)
WinHandler 获取对小部件的所有权

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

选项3:

(对于使用较新编译器的用户)
WinHandler 共享控件的所有权

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

解决方案是可以的,但要注意内存泄漏:不要忘记删除所有内容:)