【问题标题】:C26434 Function xxx hides a non-virtual functionC26434 函数 xxx 隐藏了一个非虚拟函数
【发布时间】:2021-07-28 08:01:40
【问题描述】:

拿这个简单的代码:

void CRestoreSettingsDlg::OnSize(UINT nType, int cx, int cy)
{
    CResizingDialog::OnSize(nType, cx, cy);

    m_gridBackupLog.ExpandLastColumn();
}

为什么会被标记?

C26434 函数'CRestoreSettingsDlg::OnSize' 隐藏了一个非虚函数'CRestoreDialogDlg::OnSize'

如你所见,我调用了基类方法。


声明和定义

  • CRestoreSettingsDlg:

public:
    afx_msg void OnSize(UINT nType, int cx, int cy);

void CRestoreSettingsDlg::OnSize(UINT nType, int cx, int cy)
{
    CResizingDialog::OnSize(nType, cx, cy);

    m_gridBackupLog.ExpandLastColumn();
}

  • CResizingDialog:
public:
    afx_msg void OnSize(UINT nType, int cx, int cy);

void CResizingDialog::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);

    Invalidate(TRUE);
}
  • 样板基类 (afxwin.h) 似乎具有:
protected:
    afx_msg void OnSize(UINT nType, int cx, int cy);

_AFXWIN_INLINE void CWnd::OnSize(UINT, int, int)
    { Default(); }

继承

  1. class CRestoreSettingsDlg : public CResizingDialog
  2. class CResizingDialog : public CDialogEx

【问题讨论】:

  • 问题实际上可能是为什么您不经常看到“错误消息”?例如,我假设您的CResizingDialog::OnSize() 函数也“隐藏”了基类函数(大概是CWnd::OnSize())。这将适用于非虚拟函数(具有afx_msg 属性,通常定义为空的函数)的许多 MFC 消息处理程序“覆盖”。
  • 也许向我们展示各种OnSize() 成员函数的确切定义/声明,看看它们的签名是否存在奇怪但微妙的差异。
  • 这个链接可能很有趣:docs.microsoft.com/en-us/cpp/code-quality/c26434。还向我们展示了在 .h 文件中出现的 CResizingDialog::OnSizeCRestoreSettingsDlg::OnSize 的确切声明。
  • @AdrianMole 问题已更新。
  • @Jabberwocky,请参阅docs.microsoft.com/en-us/cpp/code-quality/… 以启用这些警告

标签: visual-c++ mfc code-inspection


【解决方案1】:

C26434 warning documentation 链接到C.128 C++ Core Guidelines Rule。它解释了为了强制正确使用虚函数,非虚函数隐藏应该产生警告。

但是,对于 MFC 消息映射,您必须按照宏中指定的方式命名消息处理程序,在这种情况下为 OnSize,并且由于消息处理程序已经由虚拟函数调度(隐藏在 *_MESSAGE_MAP() 宏中) ,消息处理程序本身不必是虚拟的。

因此它可能被视为虚惊一场。或者可能被 MFC 本身视为违反上述 C.128 规则。不足为奇 - MFC 比这些指南早了几十年。

所以我想你可以继续为所有afx_msg 函数取消它。也许重新定义afx_msg 以包含__pragma(warning(suppress(...))),或者只是在afx_msg 块周围进行抑制。


一些抑制选项 (Godbolt's compiler explorer demo):


#define afx_msg // this is normally defined by MFC

struct base
{
    afx_msg void OnSize(){}
};


struct derived1 : base
{
    afx_msg void OnSize() {} // produces C26434
};

// Suppression by adding some code:

struct derived2 : base
{
#pragma warning(push)
#pragma warning(disable:26434)
    afx_msg void OnSize() {} 
#pragma warning(pop)
};

struct derived3 : base
{
    [[gsl::suppress(c.128)]] afx_msg void OnSize() {}
};


// Suppression by redefining MFC macro -- dirty but less intrusive:

#undef afx_msg
#define afx_msg __pragma(warning(suppress:26434))


struct derived4 : base
{
    afx_msg void OnSize() {} 
};


#undef afx_msg
#define afx_msg [[gsl::suppress(c.128)]]


struct derived5 : base
{
    afx_msg void OnSize() {}
};

【讨论】:

  • 谢谢。是否有示例说明如何执行这些不同的抑制方法?
  • @AndrewTruckle,添加示例
猜你喜欢
  • 1970-01-01
  • 2013-11-13
  • 2012-10-21
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 2014-11-04
相关资源
最近更新 更多