C ++:(((A *)nullptr)-> foo();是合法的吗? [英] C++ : ((A*)nullptr)->foo(); is legal?

查看:64
本文介绍了C ++:(((A *)nullptr)-> foo();是合法的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在深入研究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:

如果为对象调用了类 X 的非静态成员函数该行为不是 X 类型,也不是从 X 派生的类型是未定义的.

If a non-static member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined.

想必,编写此函数的人都知道,在这种特殊情况下,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();是合法的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆