Why can I call a non-const member function pointer from a const method?

前端 未结 5 785
终归单人心
终归单人心 2020-12-11 05:42

A co-worker asked about some code like this that originally had templates in it.

I have removed the templates, but the core question remains: why does this compile O

5条回答
  •  执念已碎
    2020-12-11 06:19

    The constness of execute() only affects the this pointer of the class. It makes the type of this a const T* instead of just T*. This is not a 'deep' const though - it only means the members themselves cannot be changed, but anything they point to or reference still can. Your object member already cannot be changed, because references cannot be re-seated to point to anything else. Similarly, you're not changing the F member, just dereferencing it as a member function pointer. So this is all allowed, and OK.

    The fact that you make your instance of CX const doesn't change anything: again, that refers to the immediate members not being allowed to be modified, but again anything they point to still can. You can still call const member functions on const objects so no change there.

    To illustrate:

    class MyClass
    {
    public:
        /* ... */
    
        int* p;
    
        void f() const
        {
            // member p becomes: int* const p
            *p = 5;   // not changing p itself, only the thing it points to - allowed
            p = NULL; // changing content of p in const function - not allowed
        }
    };
    

提交回复
热议问题