【发布时间】:2013-02-17 22:11:31
【问题描述】:
我有一个抽象的module 类,特定模块派生自该类。在运行时,我会解析一个配置文件并确定配置文件中每个模块的具体模块类型:
std::vector<module*> modules;
module *temp;
//Let nm be the result of parsing as a std::string
if(nm == "type1")
{
temp = new module_1(...);
}
else if(nm == "type2")
{
temp = new module_2(...);
}
else if(nm == "type3")
{
temp = new module_3(...);
}
else
{
//Syntax error
return -1;
}
modules.push_back(temp);
partition p;
p.modules = modules;
将向量 modules 传递给 partition 类:
class partition
{
public:
//Member functions
private:
//...Other variables
std::vector<module*> modules;
};
用完这些模块指针后,为这些模块指针释放内存的正确方法是什么?我试图在 partition 类的析构函数中删除它们,如下所示,但最终出现了分段错误:
partition::~partition()
{
for(unsigned i=0; i<modules.size(); i++)
{
delete modules[i];
}
}
【问题讨论】:
-
您为什么决定使用
std::vector<module*>而不是std::vector<module>? -
@LihO 我假设他正在使用虚函数。
-
@Adam27X 我的直接猜测是您正在双重删除您的模块。使用私有复制构造函数来禁止复制。
-
@Lalaland 我的直接想法也是,除了在那种情况下,他不应该得到双重释放/堆损坏错误吗?至少在 gcc 中,这些与段错误不同。
-
你用
gdb看过这个吗?它死在哪里?
标签: c++ memory-management memory-leaks