问题描述
在深入研究MFC时,我发现了以下代码:
While digging deep into MFC, I found this code:
_AFXWIN_INLINE HWND CWnd::GetSafeHwnd() const
{ return this == NULL ? NULL : m_hWnd; }
似乎是以这种方式使用的.
It seems to be used in this way.
CWnd *pWnd = nullptr;
pWnd->GetSafeHwnd(); // NULL
pWnd = /* something */;
pWnd->GetSafeHwnd(); // window handle
在这一点上,我很困惑-我们现在使用 NULL 对象调用成员函数!怎么会是合法的C ++?
At this point, I've got confused - we're now calling a member function with NULL object! How can it be legal C++?
推荐答案
就语言而言,这是最明确的未定义行为.§9.3.1[class.mfct.non-static]/p2:
This is the plainest of undefined behavior as far as the language is concerned. §9.3.1 [class.mfct.non-static]/p2:
想必,编写此函数的人都知道,在这种特殊情况下,Microsoft的编译器不会做任何疯狂的事情,因为安全"调用null CWnd *
似乎是重点它的存在(!).
Presumably, whoever wrote this function knows that Microsoft's compiler won't do anything crazy in this particular case, as being "safe" to call on a null CWnd *
appears to be the whole point for its existence(!).
这篇关于C ++:(((A *)nullptr)-> foo();是合法的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!