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

前端 未结 4 719
别那么骄傲
别那么骄傲 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 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 
    
    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;).

提交回复
热议问题