【发布时间】:2021-11-12 01:25:08
【问题描述】:
我想知道如果我们有一个函数参数是对const 函数的引用会发生什么,如下所示。
版本 1
int anotherFunc()
{
std::cout<<"inside anotherFunc"<<std::endl;
return 5;
}
void func(decltype(anotherFunc) const &someFunction)//note the const here
{
std::cout<<"inside func"<<std::endl;
std::cout<<someFunction()<<std::endl;
}
int main()
{
std::cout << "Hello World" << std::endl;
func(anotherFunc);
return 0;
}
第 2 版
int anotherFunc()
{
std::cout<<"inside anotherFunc"<<std::endl;
return 5;
}
void func(decltype(anotherFunc) &someFunction)//note the missing const here
{
std::cout<<"inside func"<<std::endl;
std::cout<<someFunction()<<std::endl;
}
int main()
{
std::cout << "Hello World" << std::endl;
func(anotherFunc);
return 0;
}
我的问题是:
- 就函数
func的函数参数someFunction而言,版本1 和版本2 是否完全等效?那就是为函数参数添加constsomeFunction什么都不做(即,简单地忽略)。 - 如果
const在这些示例中被忽略,那么 C++ 标准在什么时候(文档)指定在这种情况下const将被忽略。
PS:查看生成的程序集,似乎 const 被忽略以引用函数参数。
【问题讨论】:
标签: c++ function c++11 c++14 pass-by-reference