为什么我不能声明对可变对象的引用?("引用不能声明为可变")

Mar*_*tin 26 c++ reference

假设我们有test.cpp以下内容:

class A;

class B
{
    private:
        A mutable& _a;
};
Run Code Online (Sandbox Code Playgroud)

汇编:

$> gcc test.cpp
test.cpp:6:20: error: reference ‘_a’ cannot be declared ‘mutable’ [-fpermissive]
Run Code Online (Sandbox Code Playgroud)

我的gcc:

$> gcc --version
gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Run Code Online (Sandbox Code Playgroud)

为什么?

Pav*_*lev 38

没有理由让参考成员变得可变.为什么?因为const成员函数可以更改类成员引用的对象:

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;
};
Run Code Online (Sandbox Code Playgroud)


zch*_*nah 12

根据标准:[7.1.1第8段]:

"mutable说明符只能应用于类数据成员(9.2)的名称,不能应用于声明为const或static的名称,也不能应用于引用成员."

所以这只是非法的.


Jon*_*Jon 11

只能在构造对象时分配引用,此后不能修改引用.因此,制造它们mutable没有任何意义,这就是标准不允许它的原因.

  • 但是引用可以是const或非const.所以'可变的A&a`应该没问题,不应该吗?(现在不在编译器附近.) (2认同)
  • 但在这种情况下,`mutable`适用于引用的对象,而不是引用. (2认同)

vis*_*tor 5

这可能会让您大吃一惊,但引用永远不会可变(不能引用另一个对象)并且被引用的值始终是可变的(除非您有对 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';
}
Run Code Online (Sandbox Code Playgroud)

const 方法意味着将顶级 const 限定符添加到成员中。对于引用,它什么都不做 (= int & const a;),对于指针,它生成指针,而不是指针对象 const (= int* const p,not const int* p;)。