【发布时间】:2012-09-23 07:13:07
【问题描述】:
在我的项目中,我有两个类,EarleyParser 类:
class EarleyParser
{
public:
EarleyParser();
virtual ~EarleyParser();
void initialize( string filePath, bool probabilityParse );
private:
bool probabilityParser;
typedef unordered_map< string, list<Production> > productionHashTable;
productionHashTable earlyHashTable;
};
还有Production 类:
class Production
{
public:
Production();
Production( float productionProbability, int productionLength, vector< string >* productionContent );
Production( const Production& copy_me );
virtual ~Production();
float getProductionProbability();
int getProductionLength();
vector< string >* getProductionContent();
private:
float productionProbability;
int productionLength;
vector< string >* productionContent;
void setProductionProbability( float productionProbability );
void setProductionLength( int productionLength );
void setProductionContent( vector< string >* productionContent );
};
正如您在上面看到的,EarlyParser 类有一个成员元素,它是 unordered_map,其键元素是字符串,值是 list 元素的 list 来自 Production 类。
代码工作正常,unordered_map 和 list 被填充,但是在调用 EarleyParser 的标准析构函数类时,我遇到了分段错误。
据我了解,EarleyParser 的默认析构函数应该调用unordered_map 的默认析构函数,它应该调用list 之一,它应该为它的每个元素调用Production 类的默认析构函数, 如下:
Production::~Production()
{
if( this->productionContent != NULL )
delete this->productionContent; <- line 44
}
使用 Valgrind 和 GDB 进行回溯并没有给我太多帮助来解决分段错误,这在析构函数第 44 行的EarleyParser.cpp 中给出。
我应该实现析构函数类,还是应该使用默认析构函数? 关于可能导致分段错误的任何想法?
添加的副本构造函数
Production::Production( const Production& copy_me )
{
if( this->productionContent != NULL )
this->productionContent = NULL;
this->setProductionProbability( copy_me.productionProbability );
this->setProductionLength( copy_me.productionLength );
this->setProductionContent( copy_me.productionContent );
}
【问题讨论】:
-
在您的复制构造函数中,您是只复制指针还是进行“深度”复制? 为什么你有一个指向容器的指针?为什么不用参考?
-
Production的复制 ctor 是什么样的,为什么你的析构函数是虚拟的?另外,Production是否也拥有vector?如果是,为什么是指针,如果不是,为什么要删除它? -
vector< string >* getProductionContent();这让我恶心。 Urgh 指向容器的指针。 -
@Xeo - 我添加了复制构造函数
-
@TonyTheLion - 我用这个选项编译
std=c++0x,所以我相信是的......
标签: c++ segmentation-fault destructor delete-operator