![](/img/trans.png)
[英]C++ Difference Between Const Reference to Non Const Object and Non Const Reference to Non Const Object
[英]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;
}
我的问题是:
func
的函数参数someFunction
而言,版本 1 和版本 2 是否完全等效? 那就是为函数参数someFunction
添加const
什么都不做(即简单地忽略)。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 和版本 2 在函数 func 的函数参数 someFunction 方面是否完全等效?
是的。 没有 const 限定的函数类型,也没有 const 函数的引用。 如果您将 const 应用于对函数类型的显式书面引用,那么程序将是错误的。 但是当 const 应用于类型别名或类型推导时,const 将被忽略。
- C++ 标准是否指定在这种情况下将忽略 const 。
是的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.