c++ - 为什么别名 int& 允许创建非函数类型 const (int&)?

标签 c++

通常在使用常量引用时会出现编译器错误,但在使用别名或使用模板时不会。为什么会这样?

int a = 5;
using my_t = int&;
my_t const b = a; //#1 OK 
int& const c = a; //#2 Compiler error

当运行最新的 clang 编译器(x86-64 clang(实验性 P1144))时,#1 给我警告:

[x86-64 clang (experimental P1144) #1] warning: 'const' qualifier on reference type 'my_t' (aka 'int &') has no effect [-Wignored-qualifiers]

#2 给出了错误:

[x86-64 clang (experimental P1144) #1] error: 'const' qualifier may not be applied to a reference.

x86-64 gcc (trunk) 给出了#2 的错误但没有给出#1 的错误。

最佳答案

这只是规则。来自 [dcl.ref]/1 :

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name ([dcl.typedef], [temp.param]) or decltype-specifier, in which case the cv-qualifiers are ignored.

它的存在是为了让编码更容易。 int& const 显然是错误的,允许它没有任何好处。 T const 可能对某些 T 有效,因此在无效时拒绝它会非常有害 - 如果您允许它并忽略无效的代码,它会更容易编码这些情况下的 cv 限定符。

关于c++ - 为什么别名 int& 允许创建非函数类型 const (int&)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51404206/

相关文章:

c++ - 打印 C++ 编译器名称

c++ - 如何使用 fprintf/printf 打印破折号或点?

c++ - 通过类型的变量键入特征

c++ - 如何使用另一个模板化类的实例来对类进行模板化?

c++ - 具有空 mem-initializer-list 和空主体的构造函数

c++ - 更改窄字符串编码或缺少 std::filesystem::path::imbue

c++ - 将delphi记录 "polymorphic"转换为c/c++

c++ - 重新启动 C++ 程序

c++ - 在循环和函数中使用用户输入

c++ - LNK2019 当试图继承一个类时