Jes*_*ire 5 c++ embedded const-correctness
我是一名嵌入式C开发人员,他最近开始在嵌入式设备上搞乱C++代码,当一个类访问外部设备上的内存映射寄存器或数据等易失性数据时,我不确定如何应用const-correctness.模数转换器(ADC).
例如,我有通过指针访问其内存映射寄存器来连接设备硬件模块的类,如下所示:
class IOPin
{
public:
/* Constructor, destructor, other methods...*/
// should this be a const method?
bool ReadIOState() {return portregs_->state;}
private:
/* Other private stuff...*/
// Constructor points this to the right set of memory-mapped registers
volatile struct portregs_t
{
uint32_t control;
uint32_t state;
uint32_t someotherreg;
} *portregs_;
};
Run Code Online (Sandbox Code Playgroud)
寄存器名称当然是为了举例说明.我正在为任何好奇的人使用Microchip PIC32器件.
根据我可能不正确的理解,标记方法const
意味着对象的可观察状态不应该改变.所以,应该在ReadIOState()
方法不是const
因为它访问volatile
,可以在任何时候改变,因此调用者会观察到变化数据?或者应该是const
因为该方法没有明确改变任何东西?
目前,const
由于问题中所述的原因,我倾向于不采用该方法.在找到这篇GotW文章之后尤其如此,该文章指出其含义const
正在改变为"能够同时阅读".我的嵌入式应用程序是单线程的,但我认为这对于const
一般情况来说可能是一个很好的试金石.
另外,编译器如何处理const
方法?也就是说,当我想像这样轮询IO的状态时会发生什么:
// wait for IO pin to go high
while(!myIOpin.ReadIOState())
{}
Run Code Online (Sandbox Code Playgroud)
如果ReadIOState()
是const
,那么编译器是否可以重用一次调用后返回的值,或者它是否足够智能以查看它是否正在访问volatile
数据而不是这样做?