int main(){
int x = 10;
const int&z = x;
int &y = z; // why is this ill formed?
}
为什么将常量引用的非常量引用初始化为常量引用不正确?这背后的原因是什么?
答案 0 :(得分:9)
那么,为什么它不应该形成不良?
它是错误的,因为它打破了const correctenss的明显规则。在C ++语言中,不允许将常量访问传递隐式转换为非常量访问路径。指针和引用都是一样的。这就是拥有持续访问路径的全部目的:防止修改路径所导致的对象。一旦你使它保持不变,就不允许你回到非常数,除非你使用const_cast
做出明确而有意识的努力。
在这种特殊情况下,您可以使用const_cast
轻松地从访问路径中删除constness(这是const_cast
的用途)并合法修改引用的对象,因为引用的对象不是真的恒定
int main(){
int x = 10;
const int &z = x;
int &y = const_cast<int &>(z);
y = 42; // modifies x
}
答案 1 :(得分:1)
由于y
不是const
,您可以撰写y = 42
并更改z
(const
)。
答案 2 :(得分:1)
因为const引用是不可修改的,而标准引用是。
答案 3 :(得分:1)
编译器假定const int&amp; amp;是一个const int,即使在这种情况下它不是。你不能使非const引用引用const int,因为你可以通过引用改变(概念上)const int。
答案 4 :(得分:0)
由于
int const x = 10;
int const& z = x;
int& y = z;
y = 42;
会修改常量变量。
答案 5 :(得分:0)
正如其他人所说,它会允许人们间接改变x
,这会打破常规的承诺。见http://en.wikipedia.org/wiki/Const_correctness