[英]What's wrong with defining a reference to a pointer to a const data with non-const pointer?
int main()
{
const int* x;
int* pa = x;//removes const, so UB.
const int*& pb = pa;//error
int* pd = pb;//error
return 0;
}
I know that it's not possible to define a pointer to non-const data
with a pointer to const data
, because it would automatically cancel the constness out allowing me to modify the value. 我知道用
pointer to non-const data
的pointer to const data
定义一个pointer to non-const data
的pointer to const data
不可能的,因为它会自动取消pointer to const data
,允许我修改该值。
But what is wrong with the second initialization? 但是第二次初始化有什么问题? I know that a reference is an alias of something and how it works, but still don't get what actually is happening there at all.
我知道引用是某个东西的别名以及它是如何工作的,但仍然没有得到实际发生的事情。 I guess that explanation of the second error will, hopefully, enlighten me the third error.
我想对第二个错误的解释有望使我对第三个错误有所启发。
Can anyone shed some light? 任何人都能解释一下吗? Thanks!
谢谢!
const int x = 1;
int* p;
const int*& r = p;
Imagine we had gotten this far. 想象一下,我们已经走到了这一步。 This last line will give the error you're questioning, but let's assume it works.
最后一行将给出您正在质疑的错误,但让我们假设它有效。 Now
r
and p
refer to the same pointer object. 现在
r
和p
引用相同的指针对象。 But now we can do this: 但是现在我们可以这样做:
r = &x;
This makes r
point at the const
object x
, which you might think is fine, but it will also make p
point at it. 这使得
r
指向const
对象x
,您可能认为它很好,但它也会使p
指向它。 Since p
is an int*
(not const
), we can now use p
to modify x
: 由于
p
是int*
(不是const
),我们现在可以使用p
来修改x
:
*p = 2;
Now we've changed the value of a const
object. 现在我们已经改变了
const
对象的值。 The error in question prevents us from doing this. 有问题的错误阻止我们这样做。
So basically, the reasoning for this error is that being able to bind a reference to pointer to const
to a pointer to non- const
would give you a way to get the non- const
pointer to point at a const
object. 所以基本上,这个错误的原因是能够将对
const
的指针的引用绑定到指向非const
的指针,这将为您提供一种方法来使非const
指针指向const
对象。 That's bad. 那很糟。
See the Why am I getting an error converting a Foo**
→ Foo const**
C++ FAQ to learn about the same issue but with pointers instead of references. 请参阅为什么我在转换
Foo**
→ Foo const**
C ++ FAQ 时遇到错误,以了解相同的问题但使用指针而不是引用。 The reasoning is the same. 推理是一样的。
This is just another instance of the rule that you cannot bind a temporary to a non-const refence. 这只是规则的另一个实例,您不能将临时绑定到非const refence。
Eg 例如
X f();
X& r = f(); // illegal
X const& cr = f(); // OK
You can convert a pointer to int
to a pointer to const int
but the result of that conversion is a new pointer with a different type. 您可以将指向
int
的指针转换为指向const int
的指针,但该转换的结果是具有不同类型的新指针。 You cannot bind an rvalue (such as the result of this conversion) to a non-const reference, only to a const reference, eg 您不能将rvalue(例如此转换的结果)绑定到非const引用,仅绑定到const引用,例如
const int* const& pb = pa; // pb is not bound directly to pa but to
// the result of converting pa to const int*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.