Why can't I declare a reference to a mutable object? (“reference cannot be declared mutable”)

前端 未结 4 627
别那么骄傲
别那么骄傲 2021-02-05 04:04

Let\'s say we have a test.cpp as follows:

class A;

class B
{
    private:
        A mutable& _a;
};

Compilation:



        
4条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 04:56

    There is no reason to have a reference member mutable. Why? Because const member functions can change the object which is referenced by a class member:

    class B {
    public:
        B(int var) : n(var) {};
        void Set(int val) const { n = val; }  //no error
        void SetMember(int val) const { m = val; }  //error assignment of member `B::m' in read-only structure
    protected:
        int& n;
        int m;
    };
    

提交回复
热议问题