我有一个C ++代码如下:
tryIt.h文件
class tryIt : public someOtherClass
{
public:
bool insertI ();
private:
CommandI* m_pInsertI;
bool createInsertI();
}
tryIt.cpp文件
tryIt ::tryIt () : m_pInsertI(NULL)
{
createInsertI();
}
tryIt ::~tryIt ()
{
if(m_pInsertI!=NULL)
{
delete m_pInsertI;
m_pInsertI=NULL
}
}
bool createInsertI()
{
m_pInsertI = returnFromSomeOtherFunction();
return true;
}
bool insertI()
{
// Over here if I use m_pInsertI anyhow my code fails with seg fault
// even checking if(m_pInsertI==NULL) make the code throw seg fault
}
所以问题是触摸m_pInsertI使我的代码抛出Seg。故障(信号11)。甚至用GDB调试了代码,但没有得到任何有用的信息。
编译器是GCC
请帮忙。
答案 0 :(得分:0)
听起来这个类的实例不存在或已损坏。 这就是为什么你不能访问它的任何成员,即使(m_pInsertI == NULL)检查引发异常。
答案 1 :(得分:0)
不应该
bool createInsertI()
是
bool tryIt::createInsertI()
与insertI()
相同答案 2 :(得分:0)
我看到以下两种可能性:
returnFromSomeOtherFunction()
已经返回一个损坏的指针示例(违规三条规则)
tryIt instance1; // allocates instance2.m_pInsertI
{
tryIt instance2;
instance1 = instance 2; // performs a shallow copy
} // here, instance2.m_pInsertI is deleted
instance1.insertI(); // access violation
<强>建议:强>
这是否会导致您的问题:不要实施手动内存管理。只需使用std::unique_ptr<CommandI>
代替m_pInsertI
,这样就不需要实现析构函数或复制构造函数/运算符。