/*
  The following piece of code should not compile:

  According to [12.3.2/1], the conversion function
  operator X&() cannot be called. However, its
  presence tricks the compiler into thinking that
  I has a license to initialize a non-const X& from a
  const X&. This is illegal by [8.5.3/5].

  I think that diagnostics is required in this case.

  Instead, g++ compiles this code, but the program
  segfaults.
*/

struct X {

  int x;

  X ( int i = 0 )
    : x ( i )
  {}

  operator X & ( void ) const {
    return ( *this );
  }

};

void add_one ( X & ref ) {
  ++ ref.x;
}

#include <iostream>

int main ( void ) {
  X const a ( 2 );
  add_one( a );
  std::cout << a.x << '\n';
}


-- 
           Summary: g++ accepts const-incorrect code due to conversion
                    function
           Product: gcc
           Version: 4.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: jkherciueh at gmx dot net


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26698

Reply via email to