gpt4 book ai didi

我们可以修改 const 变量的值吗?

转载 作者:太空狗 更新时间:2023-10-29 17:16:10 26 4
gpt4 key购买 nike

来自 this article .

Another use for declaring a variable as register and const is to inhibit any non-local change of that variable, even trough taking its address and then casting the pointer. Even if you think that you yourself would never do this, once you pass a pointer (even with a const attribute) to some other function, you can never be sure that this might be malicious and change the variable under your feet.

我不明白我们如何通过指针修改const 变量的值。这不是未定义的行为吗?

const int a = 81;
int *p = (int *)&a;
*p = 42; /* not allowed */

最佳答案

作者的观点是,使用 register 存储类声明变量会阻止您获取其地址,因此无法将其传递给可能通过丢弃 const 来更改其值的函数

void bad_func(const int *p) {
int *q = (int *) p; // casting away const
*q = 42; // potential undefined behaviour
}

void my_func() {
int i = 4;
const int j = 5;
register const int k = 6;
bad_func(&i); // ugly but allowed
bad_func(&j); // oops - undefined behaviour invoked
bad_func(&k); // constraint violation; diagnostic required
}

通过将潜在的 UB 更改为约束违规,需要进行诊断并且(需要)在编译时诊断错误::

5.1.1.3 Diagnostics

1 - A conforming implementation shall produce at least one diagnostic message [...] if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined.

6.5.3.2 Address and indirection operators

Constraints

1 - The operand of the unary & operator shall be [...] an lvalue that designates an object that [...] is not declared with the register storage-class specifier.

请注意,register 数组对象上的数组到指针衰减是未定义的行为,不需要进行诊断 (6.3.2.1:3)。

另请注意,在 C++ 中,register 左值 允许获取地址,其中 register 只是一个优化器提示(并且已弃用一个)。

关于我们可以修改 const 变量的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12245333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com