C++ const method on non const pointer member

后端 未结 4 1087
礼貌的吻别
礼貌的吻别 2020-12-19 10:33

I was wondering how protect a non const pointer member from an object throught a const method. For example:

class B{
    public:
        B(){
            thi         


        
4条回答
  •  离开以前
    2020-12-19 11:03

    The problem you have is that a const method makes all the member variables const. In this case however, it makes the pointer const. Specifically, it's as if all you have is B * const b, which means a constant pointer to a (still) mutable B. If you do not declare your member variable as const B * b, (that is, a mutable pointer to a constant B), then there is no way to protect from this behavior.

    If all you need is a const B, then by all means, define A like this:

    class A {
    public:
        A() : b(new B) {}
    
        // This WILL give an error now.
        void changeMemberFromConstMethod() const { b->setVal(); }
    private:
        const B* b;
    }
    

    However, if other methods of A mutate B, then all you can do is make sure that B does not get mutated in your const methods of A.

提交回复
热议问题