Why does comparing a member function pointer to NULL generate a warning?

The following bit of code compiles without warning for Windows, Mac, and iOS:

class MyClass {
    SomeOtherClass * m_object;
    void (SomeOtherClass::*m_callback)();
public:
    MyClass(SomeOtherClass * _object,void (SomeOtherClass::*_callback)()=NULL) :
        m_object(_object),m_callback(_callback) {}

    void DoStuff() {
        //generates warning: NULL used in arithmetic when compiling with the Android NDK
        if (NULL==m_callback) {
            m_object->DoNormalCallback();
        } else {
            (m_object->*m_callback)();
        }
    }
};

Why is this warning generated and what can I do with it?

+5
source share
5 answers

I do not think that you are allowed to compare 0(or NULL) with pointers to member functions, especially since they may not be pointers (for example, if a function virtual).

Personally, I rewrote the test ifwithout comparison, for example:

void DoStuff() {
    if (m_callback) {
        (m_object->*m_callback)();
    } else {
        m_object->DoNormalCallback();
    }
}

And, for bonus points, run this int test in the constructor.

class MyClass {
    SomeOtherClass * m_object;
    void (SomeOtherClass::*m_callback)();
public:
    MyClass(SomeOtherClass * _object,void (SomeOtherClass::*_callback)()=NULL) :
        m_object(_object),m_callback(_callback)
    {
         // Use "DoNormalCallback" unless some other method is requested.
         if (!m_callback) {
             m_callback = &SomeOtherClass::DoNormalCallback;
         }
    }

    void DoStuff() {
        (m_object->*m_callback)();
    }
};
+2
source

NULL ((void*)0), . . 0 NULL. 0 - , , .

EDIT , . -, . ((void*)0) , , .

EDIT 2 , : , ++- NULL ((void*)0). , ( ).

+4

-Wno-conversion-null.

+1
source

if (m_callback)as suggested by Andre Caron, but I have never been a fan of implicit throws for bools and prefer to use a statement that evaluates bool. This is a bit verbose, but it works:

if (static_cast<void (SomeOtherClass::*)()>(NULL)==m_callback)
    m_object->DoNormalCallback();   
} else {   
    (m_object->*m_callback)();   
}

Still not sure why the GCC version for NDK needs to be broadcast.

0
source

Prior to C ++ 11, the result of comparing an element-pointer with '0' is undefined.

In C ++ 11, it is legal to compare a pointer to an element with the new C ++ 11 'nullptr' keyword

0
source

All Articles