Const正确性和硬件写入 [英] Const-correctness and hardware writes

查看:150
本文介绍了Const正确性和硬件写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下成员函数:

  void CFoo :: regWrite(int addr,int data)
{
reg_write(addr,data); // driver call to eg写固件寄存器
}

很明显,调用此函数不会修改内部状态的对象被调用。但是,它会更改 Foo 实例代表的状态。



例如这些,应该 Foo :: regWrite(int addr,int data)是一个const函数?

解决方案

你必须为类 CFoo 决定逻辑const的含义,这取决于类是什么。 / p>

如果 CFoo 被解释为是指某些数据,那么它可能是有意义的能够通过 CFoo const 实例修改该数据,在这种情况下,您的成员函数将为 const 。例如,考虑其他类型的引用一些数据 - 你可以修改 char * const const std :: unique_ptr< ; char>



如果 CFoo 被解释为拥有一些数据,那么通过 CFoo const 实例禁止修改可能是有意义的。例如,考虑容器,其中元素在逻辑上是对象状态的一部分,即使它们不是对象的物理部分。因此 vector :: operator [] 有一个const重载,返回 const T& ,而不是 T& insert 成员函数是非常量等。


Say I have the following member function:

void CFoo::regWrite( int addr, int data )
{
  reg_write( addr, data ); // driver call to e.g. write a firmware register
}

Clearly, calling this function doesn't modify the internal state of the object it is called on. However, it changes the state of whatever this Foo instance represents.

In circumstances such as these, should Foo::regWrite(int addr, int data) be a const function?

解决方案

You have to decide what the meaning is of "logically const" for the class CFoo, and that depends what the class is for.

If CFoo is construed as referring to some data, then it might make sense to be able to modify that data via a const instance of CFoo, in which case your member function would be const. For examples of this consider other types that refer to some data -- you can modify the referand of a char *const or a const std::unique_ptr<char>.

If CFoo is construed as owning some data, then it might make sense to forbid modification via a const instance of CFoo. For examples of this consider containers, where the elements are logically "part of the object's state" even when they aren't physically part of the object. So vector::operator[] has a const overload that returns a const T& rather than a T&, the insert member function is non-const, etc.

这篇关于Const正确性和硬件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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