Warning: returning reference to temporary

Martin v. Loewis martin@loewis.home.cs.tu-berlin.de
Sun Mar 12 00:47:00 GMT 2000


> Why the warning about returning reference to temporary?

Thanks for your bug report. I'm not sure this is a bug in the
compiler; it might be a bug in your code. Looking at 5.16,
[expr.cond]/4

# If the second and third operands are lvalues and have the same type,
# the result is of that type and is an lvalue.

we have to determine whether in

  const unsigned long& word() const {
    return set_width <= REPBITS ? bits : *(pbits);
  }

are both lvalues of the same type. They are certainly both
lvalues. pbits is of type (unsigned long* const), so *pbits is of type
'unsigned long'. OTOH, bits is of type 'unsigned long const', since
'this' is a const pointer. Therefore, the lvalues have not the same
type, and 5.16/5 applies

# Otherwise, the result is an rvalue.

Hence the message about returning a reference to a temporary.

If you question this line of reasoning, please discuss it in one of
the public C++ fora first, eg. comp.lang.c++.moderated, or
comp.std.c++.

Regards,
Martin


More information about the Gcc-bugs mailing list