#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/