http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52185
Bug #: 52185
Summary: Const member function may change the object for which
the function is called.
Classification: Unclassified
Product: gcc
Version: 4.7.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
AssignedTo: unassig...@gcc.gnu.org
ReportedBy: lsoltys...@gmail.com
According to paper www.open-std.org/JTC1/SC22/WG21/docs/papers/2011/n3242.pdf (
class.this point 2), a const member function shall not modify the object for
which the function is called.
With basic cases it is true, so for below class g++ returns error ('error:
increment of member ‘A::a’ in read-only object').
class A {
int a;
public: int fun() const { a++; }
};
Problems start when class contains references. In below example, const member
function allows to change internal state of class A instances. This shouldn't
be allowed. In my opinion compilation should failed, but g++ 4.7.0 doesn't
report any problem.
class A {
int a1;
int & a2;
public:
A() : a2(a1) { }
int fun() const { a2++; }
};