简体   繁体   中英

Pointer to member function with different compilers

I observed that different GCC versions behave differently when I try to get a pointer to a member function.

class Foo {
public:
    void bar() { }
};

int main() {
    void (Foo::*func1)(void) = Foo::bar; // Error with gcc 4.3.2 and gcc 7.1.0

    return 0;
}

The above code compiles fine with gcc 4.9.2 (MinGW), gcc 6.3 and clang 4.0 on windows. But results in the following error message with gcc 4.3.2 and gcc 7.1.0 (on linux):

error: invalid use of non-static member function 'void Foo::bar()'

If I change this line to explcitly request the adress via the address operator like so:

void (Foo::*func1)(void) = &Foo::bar; // Added an ampersand

It compiles without errors with all tested compilers .

Please note that there may be the same differences with other versions, this are only the one I could test.

So which one is right?

Note: This is not a duplicate of this question. I know how to fix it. My question is focused on the different compilers and why they behave differently. As fa as I know both variant should be syntactically correct, but different compiler seem to handle that in different ways.

The address-of operator (ie operator& ) is mandatory to form pointers to member function.

It's optional for pointers to non-member function or static member function , because of the function-to-pointer implicit conversion.

A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional.

But the function-to-pointer implicit conversion doesn't apply for non-static member functions.

An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.

BTW: I tried with Gcc head version and Clang head version , both failed to compile.

& is required to take address of member:

&Foo::bar

contrary to function which can decay to pointer of function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM