Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MSVC allow to call non-virtual non-static functions on a nullptr?

Note: This question is about MSVC, not about the C++ Standard!

According to the C++ standard, calling any member function (virtual or not) on nullptr is undefined behaviour (see here and here). As such I was mildly surprised that when I created a MFC Application with the Visual Studio Wizard to find this code:

void CClassView::AdjustLayout()
{
    if (GetSafeHwnd() == nullptr)
    {
        return;
    }
    //...

Where GetSafeHwnd is defined as:

_AFXWIN_INLINE HWND CWnd::GetSafeHwnd() const
    { return this == NULL ? NULL : m_hWnd; }

This makes me wonder what the rules of MSVC actually are. According to this implementation, calling a function on a nullptr seems to be fine, it's just that this is then the nullptr. Is this assumption correct for MSVC? What if the member function is virtual? What if it's pure virtual?

like image 669
Brotcrunsher Avatar asked Oct 12 '25 12:10

Brotcrunsher


1 Answers

No, it's still not allowed.

MFC gets away with it because it's closely tied to MSVC. Microsoft ensures that the MFC code continues to work as intended with new versions of MSVC. This might include non-portable solutions.

As a practical matter, MFC doesn't use virtual inheritance or multiple inheritance in cases where this check exists. So you're on even less solid ground there.

like image 172
MSalters Avatar answered Oct 14 '25 00:10

MSalters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!