指针声明为常量和易失性 [英] Pointer declared as constant as well as volatile

查看:70
本文介绍了指针声明为常量和易失性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读时,我遇到了这种类型的声明和以下行-

While reading I came across this type of declaration and the following line -

const volatile char *p=(const volatile char *) 0x30;




p的值仅受外部条件改变

The value of p is changed by external conditions only

我不了解外部条件。还有这种类型的声明的实际用法是什么?

I don't get what are the external conditions . And also what is practical use of this type of declaration?

推荐答案

const 表示程序的流程不会修改 p 所指向的内容。在尝试取消引用指针后修改值的任何操作都会导致编译时错误:

The const says that the flow of your program isn't going to modify what is pointed to by p. Any attempt to modify the value after dereferencing the pointer will result in a compile-time error:

*p = 'A'; // will not compile

请注意,这不是特别有效的合同;位置 0x30 的值仍可以通过别名非const指针更改,但 p 除外:

Note that this isn't a particularly strong contract; the value at location 0x30 can still be changed through an aliasing non-const pointer, other than p:

volatile char *q = 0x30;
*q = 'A'; // will compile

另一种打破此合同的方法是放弃 const from p

Another way to break this contract is by casting away the const from p:

*(volatile char *) p = 'A'; // will compile

volatile 不排除可能由另一个线程,内核,异步信号处理程序或有权访问相同内存空间的外部设备引起的任何修改。这样,编译器不会错误地假设 p 所指向的值不会更改,并且每次引用该值都会从内存中加载它:

The volatile, however, doesn't exclude any modifications which could be caused by another thread, the kernel, an asynchronous signal handler or an external device which has access to the same memory space. This way the compiler cannot make the wrong assumption that the value pointed to by p doesn't change and will load it from memory every time it is referenced:

/*
 The character at 0x30 will be read on every iteration,
 even if the compiler has proven that the program itself
 doesn't modify the value at that address.
*/
while (*p) {
    ...
}

如果编译器错误地优化了这种构造,它可能发出指令,该指令仅从内存中加载一次该值,然后将其保存在寄存器中。寄存器实际上是一个独立的副本,对原始位置的任何更改都不会反映在那里,并且不用说,这可能会导致一些非常讨厌的错误。

If the compiler was to erroneously optimise such a construct, it could emit instructions which load the value only once from memory and then keep it in a register. The register is essentially an independent copy and any changes to the original location will not reflect there, and, needless to say, this can cause some very nasty bugs.

这篇关于指针声明为常量和易失性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆