C++ function_pointer 和 &function_pointer 有什么区别?

C++ What's the difference between function_pointer and &function_pointer?

我正在阅读一些文档,我看到可以使用和不使用“&”来初始化函数指针:

    #include <iostream>

    int No() { return 5; }

    int main() {

        int (*f)() = &No; //method 1
        int (*f2)() = No; //method 2

        std::cout << (*f)() << std::endl; //prints out 5
        std::cout << (*f2)() << std::endl; //prints out 5

        return 0;
    }

我看不出这两种方法有什么区别。一个 "better" 比另一个好吗?这两者有什么区别吗?

函数可以隐式转换为指向函数的指针,所以没有区别(N3376 4.3/1)。

An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function.

函数指示符隐式转换为指向函数类型的指针。

来自 C++ 标准(4.3 函数到指针的转换)

1 An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function

所以这些声明

    int (*f)() = &No; //method 1
    int (*f2)() = No; //method 2

是等价的。在第一个声明中,函数指示符被显式转换为指针,而在第二个声明中,函数指示符被隐式转换为指针。

在这个语句中函数的调用中

std::cout << (*f)() << std::endl;

使用表达式 *f 是多余的,因为函数指示符 *f 再次被转换为指针。你可以只写

std::cout << f() << std::endl;

如果你愿意,你甚至可以写

std::cout << (*******f)() << std::endl;

结果是一样的。

这是一个演示程序。

#include <iostream>

int No() { return 5; }

int main() 
{
    int (*f)() = &No; //method 1
    int (*f2)() = No; //method 2

    std::cout << f() << std::endl; //prints out 5
    std::cout << ( *******f2 )() << std::endl; //prints out 5

    return 0;
}

取消引用指针 *f2 会产生函数类型的左值,该函数类型又会再次转换为函数指针。