成员函数是否应该是“const"?如果它们影响逻辑状态,但不影响按位状态?

2022-01-24 00:00:00 constants c++

我正在编写一个封装了控制硬件设备的传统 C API 的类.在一个简化的例子中,我可能有类似的东西:

I'm writing a class that wraps a legacy C API that controls a hardware device. In a simplified example, I might have something like:

class device
{
public:
    void set_request(int data) { legacy_set_req(p_device, data); }
    int get_response() const   { return legacy_get_rsp(p_device); }
private:
    device_handle_t *const p_device;
};

类本身没有按位状态;因此,我可以选择将 set_request() 声明为 const,编译器会对此感到满意.但是,从语义的角度来看,这是否是正确的方法,因为它会影响对象的 可观察 行为?(即封装的硬件设备确实有状态.)

The class itself has no bitwise state; therefore, I could choose to declare set_request() as const, and the compiler would be happy with that. However, from a semantic point-of-view, would this be the correct approach, given that it affects the observable behaviour of the object? (i.e. the encapsulated hardware device very much does have state.)

推荐答案

我相信 const 应该反映 logical const-ness,不管内部表示如何.仅仅因为你的对象只包含一个指向改变的东西的指针,并不意味着你的所有成员函数都应该是 const.

I believe that const should reflect logical const-ness, regardless of the internal representation. Just because your object contains only a pointer to something that changes, doesn't mean all your member functions should be const.

C++ 甚至具有用于内部表示的 mutable 概念,即使在概念上对象没有变化,也需要更改.const 关键字显然不是为了表示按位"常量.

C++ even has the mutable concept for internal representation that needs to change even if conceptually the object does not. The const keyword is clearly not intended to represent "bitwise" const-ness.

相关文章