为什么在常量引用的 auto 关键字中忽略 const
Why const is ignored in auto keyword on constant reference
int main()
{
int a = 10;
const int &b = a;
int &c = b; //gives error : C should a reference to a const b
auto d = b; // why const is ignored here?
d = 15;
cout << a << d;
}
在c++ Primer中,提到“const in reference type is always low-level”那为什么auto d = b
不是常量呢?
因为 auto
的类型推导规则推导为对象类型。您正在从 b
.
引用的副本初始化一个新的 int
这是设计使然。我们想创建新的 objects 而不明确指定它们的类型。通常情况下,它是一个新对象,它是其他对象的副本。如果将其推导为引用,则会破坏预期目的。
如果当初始化器是一个引用时,你希望推导的类型是一个引用,那么这可以通过 decltype(auto)
的占位符来实现:
decltype(auto) d = b; // d and b now refer to the same object
d = 15; // And this will error because the cv-qualifiers are the same as b's
因为扣除的类型是int
,而不是int&
。
这意味着 d
不是引用。
对于 auto d = b
,您声明 d
为非引用。这意味着 d
将是从 b
复制的新对象,然后 b
的引用部分将被忽略,之后,const-ness 也将被忽略。所以 d
的类型是 int
.
你可以显式声明d
作为引用,那么b
的const-ness不会被忽略。例如
auto& d = b; // the type of d is const int &
int main()
{
int a = 10;
const int &b = a;
int &c = b; //gives error : C should a reference to a const b
auto d = b; // why const is ignored here?
d = 15;
cout << a << d;
}
在c++ Primer中,提到“const in reference type is always low-level”那为什么auto d = b
不是常量呢?
因为 auto
的类型推导规则推导为对象类型。您正在从 b
.
int
这是设计使然。我们想创建新的 objects 而不明确指定它们的类型。通常情况下,它是一个新对象,它是其他对象的副本。如果将其推导为引用,则会破坏预期目的。
如果当初始化器是一个引用时,你希望推导的类型是一个引用,那么这可以通过 decltype(auto)
的占位符来实现:
decltype(auto) d = b; // d and b now refer to the same object
d = 15; // And this will error because the cv-qualifiers are the same as b's
因为扣除的类型是int
,而不是int&
。
这意味着 d
不是引用。
对于 auto d = b
,您声明 d
为非引用。这意味着 d
将是从 b
复制的新对象,然后 b
的引用部分将被忽略,之后,const-ness 也将被忽略。所以 d
的类型是 int
.
你可以显式声明d
作为引用,那么b
的const-ness不会被忽略。例如
auto& d = b; // the type of d is const int &