What are the semantics of a const member function?

后端 未结 9 737
囚心锁ツ
囚心锁ツ 2020-12-06 16:51

I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function

相关标签:
9条回答
  • 2020-12-06 17:53

    Corey is correct, but bear in mind that any member variables that are marked as mutable can be modified in const member functions.

    It also means that these functions can be called from other const functions, or via other const references.


    Edit: Damn, was beaten by 9 seconds.... 9!!! :)

    0 讨论(0)
  • 2020-12-06 17:54

    The const keyword on a member function marks the this parameter as constant. The function can still mute global data (so can't be cached), but not object data (allowing for calls on const objects).

    0 讨论(0)
  • 2020-12-06 17:54

    const methods are also allowed to modify static locals. For example, the following is perfectly legal (and repeated calls to bar() will return increasing values - not a cached 0):

    class Foo
    {
    public:
        int bar() const
        {
            static int x = 0;
            return x++;
        }
    };
    
    0 讨论(0)
提交回复
热议问题