在 C++ 中引用常量可调用对象和引用可调用对象之间的区别

Difference between Reference to a const Callable and Reference to a Callable in C++

提问人:user12002570 提问时间:9/17/2021 最后编辑:user12002570 更新时间:5/14/2022 访问量:119

问:

我想知道如果我们有一个函数参数是对函数的引用,如下所示会发生什么。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;
}

我的问题是:

  1. 版本 1 和版本 2 在函数的函数参数方面是否完全等效?也就是说,为函数添加参数不做任何操作(即简单地忽略)。someFunctionfuncconstsomeFunction
  2. 如果在这些示例中被忽略,那么C++标准在什么时间点(文档)指定在这种情况下将被忽略。constconst

PS:查看生成的程序集,似乎确实忽略了函数参数的引用。const

C++ 函数 11 C +14 按引用传递

评论


答:

3赞 eerorika 9/17/2021 #1
  1. 版本 1 和版本 2 在函数 func 的函数参数 someFunction 方面是否完全等效?

是的。没有 const 限定函数类型这样的东西,因此也没有对 const 函数的引用。如果将 const 应用于对函数类型的显式写入引用,则程序的格式将不正确。但是,当 const 应用于类型别名或类型演绎时,const 将被忽略。

  1. C++ 标准是否指定在这种情况下将忽略 const。

是的。

6赞 songyuanyao 9/17/2021 #2

是的,将限定符添加到函数类型的别名时将被忽略。const

根据标准,[dcl.fct]/7

cv-qualifier-seq 在函数声明器中的效果与在函数类型之上添加 cv-qualification 的效果不同。在后一种情况下,将忽略 cv 限定符。
[注 4:具有 cv-qualifier-seq 的函数类型不是 cv 限定类型;没有 cv 限定的函数类型。
[示例 4:

typedef void F();
struct S {
  const F f;        // OK: equivalent to: void f();
};

— 结束示例]