const_cast<> 的目的是什么?不稳定?

发布于 2024-09-05 09:23:48 字数 28 浏览 2 评论 0 原文

我看到可以做到这一点,但我不明白这种兴趣。

I saw it was possible to do it but I do not understand the interest.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岛徒 2024-09-12 09:23:49

constvolatile 听起来好像它们在变量上引用了相同的想法,但事实并非如此。当前代码无法更改 const 变量。易失性变量可能会被当前代码之外的某些外部实体更改。可能有一个 const 易失性变量 - 特别是像内存映射寄存器这样的变量 - 它会在程序无法预测的时间被计算机更改,但不允许你的代码直接更改。您可以使用 const_cast 向变量添加或删除 const易失性(“cv-qualification”)。

const and volatile sound like they refer to the same idea on a variable, but they don't. A const variable can't be changed by the current code. A volatile variable may be changed by some outside entity outside the current code. It's possible to have a const volatile variable - especially something like a memory mapped register - that gets changed by the computer at a time your program can't predict, but that your code is not allowed to change directly. You can use const_cast to add or remove const or volatile ("cv-qualification") to a variable.

橙幽之幻 2024-09-12 09:23:49

constvolatile 是正交的。

const 表示数据是只读的。

易失性表示变量可能由于外部原因而发生变化,因此编译器每次引用该变量时都需要从内存中读取该变量。

因此,删除 const 允许您写入原本是只读的位置(代码必须具有一些特殊的知识,该位置实际上是可修改的)。您不应该删除 易失性 来写入它,因为您可能会导致未定义的行为(由于 7.1.5.1/7 - 如果尝试引用使用 易失性限定定义的对象通过使用左值类型
对于非易失性限定类型,程序行为是未定义的。

const and volatile are orthogonal.

const means the data is read-only.

volatile means the variable could be changing due to external reasons so the compiler needs to read the variable from memory each time it is referenced.

So removing const allows you to write what was otherwise a read-only location (the code must have some special knowledge the location is actually modifiable). You shouldn't remove volatile to write it because you could cause undefined behavior (due to 7.1.5.1/7 - If an attempt is made to refer to an object defined with a volatile-qualified type through the use of an lvalue
with a non-volatile-qualified type, the program behaviour is undefined.
)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文