我正在阅读其他人的代码,其中包含类似于
boost::function
或 std::function
的自定义函数类。他们通过不断的引用来传递这些函数类。在关键路径的一节中,他们选择使用函数指针,但仍然通过不断引用来提高效率
他们的代码中有与此等效的内容:
using FuncT = int(*)(int, int);
这是这样流传的:
const FuncT&
我认为
const FuncT&
的传递效率并不比 FuncT
更有效,而且语法只是最初作为自定义函数类的剩余部分。然而,这让我想知道const FuncT
的含义是什么
#include <iostream>
using FuncT = int(*)(int, int);
struct MyClass final {
static int myMethod(int a_arg1, int a_arg2) {
std::cout << a_arg1 << " " << a_arg2 << std::endl;
return 0;
}
// Similar to what I found in someone's code
void v1(const FuncT& a_func) { a_func(1, 1); }
// A reference to a const function pointer seems meaningless, it should be
// just as efficient to copy the pointer
void v2(const FuncT a_func) { a_func(2, 2); }
// ^
// Removed reference
// I believe this is the syntax for a function pointer that cannot be
// modified to point to a different function
void v3( int(* const a_func)(int, int)) { a_func(3, 3); }
// ^
// Added const not present in FuncT
// This compiles but I don't know what the intended meaning of the extra
// const would be
void v4(const int(* const a_func)(int, int)) { a_func(4, 4); }
// ^
// Added const not present in v3
};
int main() {
MyClass myClass;
myClass.v1(&MyClass::myMethod);
myClass.v2(&MyClass::myMethod);
myClass.v3(&MyClass::myMethod);
//myClass.v4(&MyClass::myMethod); // Doesn't compile
return 0;
}
在上面的代码中
v4
可以编译,但是最左边的const
的含义是什么?
对代码进行少量修改:
void v3( int(* const a_func)(int, int)) {
a_func = &MyClass::myMethod; // no, a_func is const
}
a_func
是 const
您无法修改它。尝试分配给它会引发错误。
这里:
void v4(const int(* const a_func)(int, int)) { a_func(4, 4); }
与上面相同,但函数的返回类型是
const int
而不是int
:
const int foo(int,int) { return 42;}
int main() {
MyClass myClass;
myClass.v4(&foo);
}