【问题标题】:Difference between Reference to a const Callable and Reference to a Callable in C++C++ 中对 const Callable 的引用和对 Callable 的引用之间的区别
【发布时间】: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;
}

我的问题是:

  1. 就函数func 的函数参数someFunction 而言,版本1 和版本2 是否完全等效?那就是为函数参数添加const someFunction 什么都不做(即,简单地忽略)。
  2. 如果 const 在这些示例中被忽略,那么 C++ 标准在什么时候(文档)指定在这种情况下 const 将被忽略。

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

【问题讨论】:

    标签: c++ function c++11 c++14 pass-by-reference


    【解决方案1】:

    是的,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();
    };
    

    ——结束示例]

    【讨论】:

      【解决方案2】:
      1. 版本 1 和版本 2 在函数 func 的函数参数 someFunction 方面是否完全等效?

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

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

      是的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 2013-08-20
        相关资源
        最近更新 更多