[英]Why does C++ require low-level const qualification on both objects when copying an object to another?
I was reading C++-Primer (by Josée Lajoie and Stanley B. Lippman) when I came across this section about top-level and low-level const
s.当我看到有关顶级和低级const
的这一部分时,我正在阅读C++-Primer (由 Josée Lajoie 和 Stanley B. Lippman 撰写)。 On one paragraph, it says that when copying an object, top level const
s are ignored.在一段中,它说复制对象时,顶级const
被忽略。
Eg.例如。
const int i = 24;
int i2 = i;
Where the top-level const
qualification in i is ignored when copied into i2 .当复制到i2时, i 中的顶级const
限定被忽略。
However, it also states然而,它也指出
On the other hand, low-level
const
is never ignored.另一方面,低级const
永远不会被忽略。 When we copy an object, both objects must have the same low-levelconst
qualification or there must be a conversion between the types of the two objects.当我们复制一个对象时,两个对象必须具有相同的低级const
限定,或者两个对象的类型之间必须进行转换。 In general, we can convert a nonconst
toconst
but not the other way around.在一般情况下,我们可以转换为非const
,以const
而不是周围的其他方法。
Now, usually when C++ has a rule like this there's a reason behind them.现在,通常当 C++ 有这样的规则时,它们背后是有原因的。 I find that understanding them is fundamental to understanding the rule and therefore making it easier to memorize (this is like understanding a mathematic concept instead of memorizing formulas).我发现理解它们是理解规则的基础,因此更容易记住(这就像理解一个数学概念而不是记住公式)。 However, there's no logical rule I find that fits into the puzzle here.然而,我发现没有符合这里谜题的逻辑规则。
As a summary, my question is:作为总结,我的问题是:
const
qualification is ignored?为什么在复制对象时会忽略顶级const
限定? (There's a section explaining why in the book too, but I can't seem to get it) (书中也有解释原因的部分,但我似乎无法理解)Copying and object doesn't change the copied object.复制和对象不会改变复制的对象。 As a result, it is immaterial whether the object copied from or copied into is
const
因此,复制自或复制到的对象是否为const
并不重要
const
is never ignored when copying an object?复制对象时从不忽略低级const
背后的原因是什么? (low-level const
qualification is needed on both objects) (两个对象都需要低级const
限定)Top level case: You make a copy of the const object, so it doesn't matter if your copy is const or not, because (assuming const-correct types) you can't modify the original via the copy.顶级情况:您制作了 const 对象的副本,因此您的副本是否为 const 并不重要,因为(假设 const 类型正确)您无法通过副本修改原始对象。
Low level case: You make a copy of a handle to another object.低级情况:您将句柄复制到另一个对象。 The original handle does not allow modification of the object it refers to.原始句柄不允许修改它所引用的对象。 Allowing to ignore the low level const would mean you can obtain a handle that allows you to modify the referred object, breaking const correctness.允许忽略低级 const 意味着您可以获得一个句柄,允许您修改引用的对象,从而破坏 const 的正确性。
It would allow this kind of craziness:它会允许这种疯狂:
// should not modify n, right?
void foo(const int& n)
{
int& mutable_n = n;
mutable_n = 42;
}
...
int n = 0;
foo(n); // should not modify n, right?
std::cout << n << '\n'; // prints 42, wat??
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.