为什么我可以使用类型别名声明 const 引用?

2024-01-10

我有一个简单的问题:据我所知,我可以声明const指向某种数据类型的指针或指向常量数据类型的指针,但我只能声明对常量数据类型的引用,而不能声明对数据类型的常量引用;事实上,引用已经是常量,因为它不能反弹到另一个对象。

所以当我尝试创建一个const ref to someDataType我收到编译时错误。但对我来说重要的是当与type alias using typedef or using. e.g:

#include <iostream>

int main() {

    int i{ 10 };
    //  int& const r1{ i }; // error: ‘const’ qualifiers cannot be applied to ‘int&’. Ok here.
    using rInt = int&; // or typedef int& rInt;
    const rInt r2{ i }; // why const is allowed here?
    ++r2; // this proves that the const is applied to the reference not to the object referred to.

    std::cout << r2 << std::endl; // 11

}

正如你在上面看到的,我可以添加const我认为在这种情况下参考文献是多余的。但为什么 C++ 允许使用类型别名而不是直接这样做呢?


因为标准是这么说的:

[dcl.ref] ... Cv 限定引用的格式不正确,除非通过使用 typedef-name ([dcl.typedef], [temp.param]) 或 decltype-specifier ( [dcl.type.simple]),在这种情况下,cv 限定符将被忽略

这类似于无法声明引用引用的方式,但可以通过 typedef 声明引用(其中引用合并为一个):

int i;
int& iref = i;
//int& & irefref = iref; // not OK
using Iref = int&;
Iref& iretypedef = iref; // OK; collapses into int&

CV 折叠规则,就像参考折叠规则一样,对于使模板和类型推导可用至关重要。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我可以使用类型别名声明 const 引用? 的相关文章

随机推荐