What can a 'const' method change?

后端 未结 5 630
遇见更好的自我
遇见更好的自我 2020-12-05 23:46

C++ methods allow a const qualifier to indicate that the object is not changed by the method. But what does that mean? Eg. if the instance variables are pointer

5条回答
  •  我在风中等你
    2020-12-06 00:08

    There are two aspects to this question:

    1. what does const mean to the compiler?
    2. how does const apply when it cannot be validated by the compiler?

    Question 1

    The first is rather simple. The compiler validates that no data members are modified (unless they are qualified as mutable). It validates this recursively: for any user-defined types, it checks that no non-const methods are invoked. For built-in types, it validates that they are not assigned.

    The transformation for pointers is T* to T*const (const pointer), not const T* (pointer to const). This means that the compiler does not validate that the object pointed to is not modified. Obviously, this leads to question 2.

    Question 2

    How does const apply when not validate by the compiler? It means whatever it should mean to your application. This is usually referred to as logical const. When to use const with respect to logical const-ness is subject to debate.

提交回复
热议问题