Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function syntax works on msvc but rejected by gcc and clang [duplicate]

I wrote the following program that is accepted by msvc but both gcc and clang rejects it.

struct C
{
    void Bar(int);
};
int main()
{
    void (C::*ptr)(int) = &(C::Bar); //compiles with msvc but both gcc and clang rejects this
}  

Live demo

Gcc says:

<source>: In function 'int main()':
<source>:7:32: error: invalid use of non-static member function 'void C::Bar(int)'
    7 |     void (C::*ptr)(int) = &(C::Bar); //compiles with msvc but both gcc and clang rejects this
      |                                ^~~
Compiler returned: 1

Which compiler is correct?


1 Answers

This is a msvc bug. The standard explicitly forbids this in expr.unary.op:

A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses.

[Note 4: That is, the expression &(qualified-id), where the qualified-id is enclosed in parentheses, does not form an expression of type “pointer to member”. Neither does qualified-id, because there is no implicit conversion from a qualified-id for a non-static member function to the type “pointer to member function” as there is from an lvalue of function type to the type “pointer to function” ([conv.func]). Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id's class. — end note]

(emphasis mine)

This means that the program is ill-formed and msvc is wrong in accepting the code.

Here is the msvc bug:

MSVC accepts invalid program involving member function pointer

like image 176
Anoop Rana Avatar answered Sep 07 '25 20:09

Anoop Rana