假设我们有一个test.cpp
如下:
class A;
class B
{
private:
A mutable& _a;
};
编译:$> gcc test.cpp
test.cpp:6:20: error: reference ‘_a’ cannot be declared ‘mutable’ [-fpermissive]
我的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.
为什么?
没有理由让引用成员可变。为什么?因为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;
};
按标准:[7.1.1第8段]:
"可变说明符只能应用于类数据的名称并且不能应用于声明为const或static的名称,不能用于参考成员。"
所以这是非法的
引用只能在构造对象时分配,之后不能修改。因此,使它们成为mutable
将没有意义,这就是标准不允许的原因。
这可能会让你大吃一惊,但是引用从来都不是可变的(不能用来引用另一个对象),并且引用的值总是可变的(除非你有对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';
}
const方法意味着将顶级const限定符添加到成员中。对于引用,它不做任何事情(= int & const a;
),对于指针,它使指针,而不是指针const (= int* const p
,而不是const int* p;
)。