【问题标题】:Assigning const int to a const pointer to int is illegal?将 const int 分配给指向 int 的 const 指针是非法的吗?
【发布时间】:2013-06-30 17:23:05
【问题描述】:

为什么以下是非法的?

extern const int size = 1024;

int * const ptr = &size;

当然应该允许指向非 const 数据的指针指向一个 const int(而不是相反)?

这是来自 C++ Gotchas item #18

【问题讨论】:

  • "当然应该允许指向非 const 数据的指针指向 const int" 为什么?
  • 使用指向非 const 事物的 const 指针,您可以更改事物。如果事物天生是 const,那就是未定义的行为。
  • “当然应该允许指向非 const 数据的指针指向一个 const int(而不是相反)?” ——你倒过来了。当然,应该允许指向 const 数据的指针指向非 const int,而且确实如此。 const 是关于如何使用某些东西,而不是它是什么类型的东西。
  • 由于您的帖子中有extern,我建议您在 Stack Overflow 上搜索“[c] extern pointer”。
  • @ThomasMatthews extern 会影响答案吗?它在我看到的示例中,因此我将其包含在此处。

标签: c++ pointers constants


【解决方案1】:

如果你真的是指其中之一

const int * const ptr = &size; 
const int * ptr = &size;

这是合法的。你的是非法的。因为那不是你能做到的

int * ptr const = &size;
*ptr = 42;

而且,你的 const 刚刚改变了。

让我们反过来看看:

int i = 1234; // mutable 
const int * ptr = &i; // allowed: forming more const-qualified pointer
*i = 42; // will not compile

我们不能在这条路上造成伤害。

【讨论】:

  • 解释各种 const 限定指针之间的区别。
  • @Skizz: const 适用于其左侧的项目:int const* const 表示“指向常量整数的常量指针”; int const* 表示“指向常量整数的非常量指针”。作为一个特例,const TT const 的含义相同,因此通常分别写成const int* constconst int*
  • @JonPurdy:我的意思是编辑答案以描述示例旁边的每一个,只是为了澄清每一个的含义。
【解决方案2】:

如果允许指向非常量数据的指针指向 const int,那么您可以使用指针来更改 const int 的值,这会很糟糕。例如:

int const x = 0;
int * const p = &x;

*p = 42;
printf("%d", x);  // would print 42!

幸运的是,以上是不允许的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多