Should member functions be “const” if they affect logical state, but not bitwise state?

后端 未结 4 1307
一个人的身影
一个人的身影 2020-12-19 03:46

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:         


        
相关标签:
4条回答
  • 2020-12-19 04:25

    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++ 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.

    0 讨论(0)
  • 2020-12-19 04:25

    Like other type and member qualifications (e.g., public, private, virtual), const expresses both intention and the language semantics (i.e., safety features) that support that intention. In this case, the intention would appear counter-intuitive, even if the underlying semantics would be safe. I wouldn't do it.

    0 讨论(0)
  • 2020-12-19 04:42

    A useful test is:

        could code with only const access to the device instance interfere with the operation of code with non-const access

    Basically, const access is meant to mean you're effectively an observer. Here, it looks as though code calling set_request(...) at time T1 then get_response() at time T3 would be seriously screwed if some supposed observer called set_request() with different parameters at time T2. For that reason, set_request(...) shouldn't be accessible to observers - it should be non-const.

    (There are caveats to the test - e.g. if a const "observer" needs a lock it can obviously affect non-const usage from another thread from a timing perspective but shouldn't do so from a functional one - but it's pretty obvious how to factor that into your analysis).

    0 讨论(0)
  • 2020-12-19 04:44

    If it changes the state, it generally should not be const. The fact that the state in question is owned remotely (i.e., in a controlled device) doesn't change that.

    0 讨论(0)
提交回复
热议问题