[英]C++ code throwing Seg. Fault
我有一個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到任何地方使我的代碼拋出段。 故障(信號11)。 甚至使用GDB調試了代碼,但沒有任何有用的信息。
編譯器是GCC
請幫忙。
聽起來此類的實例不存在或未損壞。 這就是為什么您無法訪問其任何成員,即使(m_pInsertI == NULL)檢查引發異常也是如此。
在tryIt.cpp中不應該
bool createInsertI()
是
bool tryIt::createInsertI()
與insertI()相同
我看到以下兩種可能性 :
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
,因此您無需實現析構函數或復制構造函數/運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.