在c++中对派生类使用基类指针有什么负面影响吗?
Are there any negative effects to using base class pointers on derived classes in c++?
我通常避免使用类指针,因为引用似乎更有效。但我最近被迫使用它们,因为它们是在我的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];
解决方案是可以的,但要注意内存泄漏:不要忘记删除所有内容:)
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 明确定义'static const variable in a struct'对C++ 11 及以上有什么影响吗?
- 在C++中使用异常的可能的错误处理策略是什么,它们的后果和影响是什么
- GSL 的预期 (cond) 对运行时施加的性能影响是什么?
- 传递const引用参数的意义是什么?它会产生重大影响吗
- 链接到CMake目标会产生什么影响
- "insert"对德克的引用有什么影响?
- 如果订购有什么影响..否则如果按概率陈述
- 在括号内包装初始化列表的影响是什么?
- 对象分配对二进制大小的影响是什么
- 更改静态库的"动态 RTL"设置有什么影响?
- 直接索引访问与"high"内存使用量相比的理论影响是什么? "shifted"使用"low"内存使用情况的索引访问?
- 向上转换为基类对象而不是引用有什么不良影响
- "int a(); "在C++有什么影响?
- __attribute__(__packed__))对嵌套结构有什么影响?
- dlopen是否重新加载已加载的依赖项?如果是,会产生什么影响
- 在docker中编译不同内核的代码会受到什么影响?
- 函数的返回类型对c++程序有什么影响?
- 如果在Cygwin中出现段错误,会有什么影响