c++ - 取消引用函数指针的值是什么意思

标签 c++ function-pointers

#include <iostream>

void PrintTheValue(int(*func)(int a));

int main(int argc, char **argv) {
    PrintTheValue([](int a) {return a; });
    
    return 0;
}

void PrintTheValue(int(*func)(int a)) {
    std::cout << *func << std::endl;
}
在我的理解中func ,它将是一个指向按值传递的 int 的指针。但在这种情况下,我传递了一个似乎没有在任何地方被调用的 lambda。 (所以根本没有任何值(value)?)
当我运行它时,它不会破坏程序,而是打印 00EE6F80 .
这个地址是什么意思?我不知道如何解释它。

最佳答案

In my concept of understanding the func, it would be a pointer to an int passed by value.

func是一个指向函数的指针,它需要一个 int并返回 int .

But in this case I'm passing a lambda which doesn't seem to be called anywhere.


您正在传递一个没有捕获的 lambda,它可以隐式转换为指向函数的指针。在 PrintTheValue , *func ,即对指针的取消引用导致对函数的引用,并传递给 operator<< of std::cout ,它再次转换为函数指针,然后转换为 bool带值 true (作为非空指针),那么你应该得到结果 1 (或 true 使用 std::boolalpha )。如果您想调用 func你可以func(42) (或 (*func)(42))。

关于c++ - 取消引用函数指针的值是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68045063/

相关文章:

c - Solaris 64 位上的函数指针导致堆损坏

c - 如何在以struct为指针的struct中正确定义函数指针?

c++ - C++中的函数指针语法

c++ - C++11 std::function 是否限制函数指针可以具有的参数数量?

c++ - C++函数指针中的协变和逆变?

python - 包含 vector 外积的方程

c++ - 是否可以删除此条件语句?

c++ - Qt WEBKIT 与 CMake

C++ 适当的函数返回类型返回日期时间?

C++ 结构内存布局和 OpenGL glVertexPointer?