成员函数是否应该是“const"?如果它们影响逻辑状态,但不影响按位状态? [英] Should member functions be "const" if they affect logical state, but not bitwise state?

查看:34
本文介绍了成员函数是否应该是“const"?如果它们影响逻辑状态,但不影响按位状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个封装了控制硬件设备的传统 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.

这篇关于成员函数是否应该是“const"?如果它们影响逻辑状态,但不影响按位状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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