c++: returning reference to ref arg behaves in strange way

Markus Werle markus@lufmech.rwth-aachen.de
Tue Aug 7 07:00:00 GMT 2001


Maybe the code below is _not_ ANSI, but since even
on comp.lang.c++.moderated they have no answer after 5 days
let us try this forum of experts.

The compiler _should_ at least complain.
KCC said (please explain why!):

"../experimental/StdListLoopReference.2.C", line 30: warning: initial value of
          reference to non-const must be an lvalue
    std::list<const Value*> l = (a, b, c, d); // how convenient !
                                 ^

        Recompiling StdListLoopReference.2.o
"../experimental/StdListLoopReference.2.C", line 30: warning: initial value of
          reference to non-const must be an lvalue
    std::list<const Value*> l = (a, b, c, d); // how convenient !

the KCC-compiled code prints
1
2
3
4

the gcc-compiled code prints
3
4

Which is wrong IMHO
:-(

Code:

#include <list>
#include <iostream>

struct Value {
  Value(const double d) : val(d) {}
  double val;
};


std::list<const Value*>
operator,(const Value& a, const Value& b) {
  std::list<const Value*> tmp;
  tmp.push_back(&a);
  tmp.push_back(&b);
  return tmp;
}


// BIG problem! reference makes the head bang
std::list<const Value*>&
operator,(std::list<const Value*>& li, const Value& a) {
  li.push_back(&a);
  return li;
}


int main() {
  Value a(1.0), b(2.0), c(3.0), d(4.0);

  std::list<const Value*> l = (a, b, c, d); // how convenient !

  for (std::list<const Value*>::iterator iter = l.begin();
       iter != l.end(); ++iter) {
    std::cout << (*(*iter)).val << std::endl;
  }
}




More information about the Gcc-bugs mailing list