称为错误和崩溃的纯虚拟方法

Pure virtual method called error and crash

本文关键字:虚拟 方法 崩溃 错误      更新时间:2023-10-16

又一次"纯虚拟方法称为错误",我检查了其他类似的问题,它们没有解决我的问题。我与提到的消息崩溃了。我不做任何花哨的员工。代码很大,所以只有重要的摘录:

class cCOLLECT_STR_NODES_HELPER
{
  protected:
    cCOLLECT_STR_NODES_HELPER( const std::string& searchStr,
                           const int attribute,
               const cGTI_SRCH_TREE_NAME_DLG *pDlg )
   : m_compareStr(searchStr), m_attr(attribute), pSrchDlg(pDlg) {}
    virtual ~cCOLLECT_STR_NODES_HELPER() {}
   public:
    virtual bool TreatTheNode( const cGTC_TREE_NODE *curNode ) = 0;
...
}

然后是派生类:

class cCOLLECT_STR_TOP_NODES_HELPER : public cCOLLECT_STR_NODES_HELPER
{
  public:
   cCOLLECT_STR_TOP_NODES_HELPER( const std::string& searchStr,
                               const int attribute,
                   const cGTI_SRCH_TREE_NAME_DLG *pDlg )
   : cCOLLECT_STR_NODES_HELPER( searchStr, attribute, pDlg ) {}
public:
virtual bool TreatTheNode( const cGTC_TREE_NODE *curNode );
...
}  

TreatTheNode() 是单独实现的:

bool cCOLLECT_STR_TOP_NODES_HELPER::TreatTheNode( const cGTC_TREE_NODE *curNode ) {...

然后派生类初始化:

cCOLLECT_STR_NODES_HELPER *pHelper;
  cCOLLECT_STR_TOP_NODES_HELPER helper( searchStr, attribute, this );
  pHelper = &helper;

然后 pHelper 传递到一个函数中并在那里使用:

TraverseTreeNodes( const cGTC_TREE_NODE *curNode,
               cCOLLECT_STR_NODES_HELPER *pHelper ) const
{
if ( pHelper->TreatTheNode( curNode ) )  => CRASH

项目构建成功。怎么了?

在我发现我这边的错误并删除了这个问题后,我决定取消删除并部分回答它。我相信其他人可以从这个愚蠢的错误中受益(当你在 3 小时内有截止日期时,你确实会犯错误)。

我知道这是显而易见的:实际上是我写的代码:

cCOLLECT_STR_TOP_NODES_HELPER helper( searchStr, attribute, this );
pHelper = &helper;

实际上是:

{
  cCOLLECT_STR_TOP_NODES_HELPER helper( searchStr, attribute, this );
  pHelper = &helper;
}

所以助手超出了范围...

问题是,我做了调试。 pHelper指出了一些有意义的东西,至少这就是它的样子。我仍然不确定崩溃究竟是如何发生的,但是原因很清楚。当指向的对象超出范围时,它可能是 UB。不过,如果有人描述内部发生的事情,我会接受答案。

在这种情况下,您面临空指针问题,当您将未初始化的对象传递到参数中时,pHelper 将没有值,因此将尝试使程序崩溃。