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

App*_*ker 1 c++ oop pointers

我通常避免使用类指针,因为引用似乎更有效.但我最近被迫使用它们,因为它们提供了唯一(高效且简单)的解决方案,在windows api包装器中使用window 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; }
}         
Run Code Online (Sandbox Code Playgroud)

然后我用:

if (WidgetSet[i]->ID == LOWORD(wParam)) WidgetSet[i]->Click();
Run Code Online (Sandbox Code Playgroud)

从长远来看,这种做法是否正常?由于实际存储在WidgetSet中的对象都是WinControl类的衍生物.有谁能建议更好的方法?

注意:我试图让我的问题尽可能清楚.如果你仍然无法得到我所要求的,请发表评论,我将尝试详细说明这个问题.

Mar*_*ork 6

您在窗口小部件集中存储的是指针.不是对象.您的设计存在的问题是,不清楚谁应该拥有该对象从而破坏它.

我会更改界面以明确所有权.

选项1:

WinHandler确实不是自己的小部件:

void AddWidget(Widget& w) { WCount++; WidgetSet[WCount] = &w; }
Run Code Online (Sandbox Code Playgroud)

选项2:

WinHandler 获取小部件的所有权

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

选项2a:

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

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

选项3:

(对于那些使用较新编译器的人),
WinHandler 共享小部件的所有权

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

  • 通常需要注意的是`auto_ptr`不能在STL容器中使用. (2认同)