c++ - 指向具有不同编译器的成员函数的指针

标签 c++ gcc language-lawyer pointer-to-member

我观察到,当我尝试获取指向成员函数的指针时,不同的 GCC 版本表现不同。

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;
}

以上代码在 Windows 上使用 gcc 4.9.2(MinGW)、gcc 6.3clang 4.0 编译良好。 但是在 gcc 4.3.2gcc 7.1.0 (在 linux 上)会导致以下错误消息:

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

如果我将此行更改为通过地址运算符明确请求地址,如下所示:

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

在所有经过测试的编译器上编译都没有错误

请注意,与其他版本可能存在相同的差异,这只是我可以测试的。

那么哪个是对的呢?

注意:这不是 this 的拷贝问题。我知道如何解决它。我的问题集中在不同的编译器以及为什么它们的行为不同。据我所知,这两种变体在语法上都应该是正确的,但不同的编译器似乎以不同的方式处理它。

最佳答案

address-of 运算符(即 operator&)是强制性的,以形成指向成员函数的指针。

对于 pointers to non-member function or static member function,它是可选的 ,因为函数到指针的隐式转换。

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.

但是function-to-pointer implicit conversion不适用于非静态成员函数。

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.

顺便说一句:我试过 Gcc head versionClang head version , 都无法编译。

关于c++ - 指向具有不同编译器的成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44585248/

相关文章:

c++ - 迭代 C++ 可变参数模板类型列表

c++ - 基于 CMake 平台的 Clang

c - 默认选项 GCC

c++ - 用于预填充运行时使用的对象的 ELF INIT 部分代码

c++ - C++ 不是强制要求 (cond ? string_1 : string_2) initialize a string?

c++ - C++14 中 main() 的合法定义

c++ - 如何将指针映射到 unordered_map 中的对象?

c++ - 为什么涉及虚拟继承时不能使用static_cast进行向下转换?

C++ - 如何获取特定时区的日期

c++ - 具有未使用的引用参数的 constexpr 函数——gcc vs clang