c++/3760: g++ rejects legal code

Uwe F. Mayer mayer@tux.org
Sat Jul 21 11:46:00 GMT 2001


>Number:         3760
>Category:       c++
>Synopsis:       g++ rejects legal code
>Confidential:   no
>Severity:       serious
>Priority:       medium
>Responsible:    unassigned
>State:          open
>Class:          rejects-legal
>Submitter-Id:   net
>Arrival-Date:   Sat Jul 21 11:46:00 PDT 2001
>Closed-Date:
>Last-Modified:
>Originator:     Uwe F. Mayer
>Release:        3.0
>Organization:
tux.org
>Environment:
System: Linux tosca 2.2.18 #2 Thu Mar 8 13:48:25 PST 2001 i686 unknown
Architecture: i686
host: i686-pc-linux-gnu
build: i686-pc-linux-gnu
target: i686-pc-linux-gnu
configured with: ../gcc-3.0/configure --disable-nls --prefix=/usr/local/gcc-3.0
>Description:
c++ rejects to compile a member function changing a mutable data member of
a constant object instance. Direct changes of the mutable member (if public)
are fine.
>How-To-Repeat:
Compile the program bug8.cc included below, and you will get the compile-time
error message:
$ g++ bug8.cc 
bug8.cc: In function `int main()':
bug8.cc:19: passing `const class_m' as `this' argument of `void 
   class_m::incr_i()' discards qualifiers

The program bug8.cc:
====================
#include <iostream>
using namespace std;

class class_m {
public:
  class_m() : i(0) {}
  void incr_i() {i++;}
  void print() const {cout << i << endl;}
  mutable int i;
};

int main() {
  const class_m obj_m;
  obj_m.print();
  obj_m.i++;                                // works
  obj_m.print();
  const_cast<class_m*>(&obj_m)->incr_i();   // works
  obj_m.print();
  obj_m.incr_i();                           // rejected at compile time
  obj_m.print();
}

>Fix:
Work-around: if function() is a mutator member function changing a mutable data
member of a constant object instance, use instead of:
obj_m.function()
the expression:
const_cast<class_m*>(&obj_m)->function()
>Release-Note:
>Audit-Trail:
>Unformatted:



More information about the Gcc-bugs mailing list