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

查看:89
本文介绍了如果成员函数是“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 ,编译器会满意的。然而,从语义的观点来看,这将是正确的方法,因为它影响对象的 observable 行为? (即封装的硬件设备非常具有状态。)

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 应该反映逻辑常量,无论内部表示如何。只是因为你的对象只包含一个变化的指针,并不意味着所有的成员函数应该 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天全站免登陆