繁体   English   中英

C++ 中对 const Callable 的引用和对 Callable 的引用之间的区别

[英]Difference between Reference to a const Callable and Reference to a Callable in C++

我想知道如果我们有一个引用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. 就函数func的函数参数someFunction而言,版本 1 和版本 2 是否完全等效? 那就是为函数参数someFunction添加const什么都不做(即简单地忽略)。
  2. 如果const在这些示例中被忽略,那么 C++ 标准在什么时候(文档)指定在这种情况下const将被忽略。

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

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

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

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

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

——结束示例]

  1. 版本 1 和版本 2 在函数 func 的函数参数 someFunction 方面是否完全等效?

是的。 没有 const 限定的函数类型,也没有 const 函数的引用。 如果您将 const 应用于对函数类型的显式书面引用,那么程序将是错误的。 但是当 const 应用于类型别名或类型推导时,const 将被忽略。

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

是的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM