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

前端 未结 4 626
别那么骄傲
别那么骄傲 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;
    };
    
    0 讨论(0)
  • 2021-02-05 05:01

    This could blow your mind away, but a reference is never mutable (can't be made to refer to another object) and the referenced value is always mutable (unless you have a reference-to-const):

    #include <iostream>
    
    struct A
    {
      int& i;
      A(int& n): i(n) {}
      void inc() const 
      {
        ++i;
      }
    };
    
    int main()
    {
      int n = 0;
      const A a(n);
      a.inc();
      std::cout << n << '\n';
    }
    

    A const method means that a top-level const-qualifier gets added to the members. For a reference this does nothing (= int & const a;), for a pointer it makes the pointer, not the pointee const (= int* const p, not const int* p;).

    0 讨论(0)
  • 2021-02-05 05:04

    References can only be assigned when constructing an object, and cannot be modified thereafter. Thus making them mutable would have no meaning, which is why the standard disallows it.

    0 讨论(0)
  • 2021-02-05 05:05

    According to the standard: [7.1.1 para 8]:

    "The mutable specifier can be applied only to names of class data members (9.2) and cannot be applied to names declared const or static, and cannot be applied to reference members."

    So it's just illegal.

    0 讨论(0)
提交回复
热议问题