Topic: Non-const references and rvalues


Author: dHarrison@worldnet.att.net (Doug Harrison)
Date: 1997/01/23
Raw View
I'd appreciate comments on the legality of the following fun() calls:

 class A {};
 A    GetA()    { return A(); }
 void fun(A& a) {}
 int main()
 {
    fun(A());
    fun(GetA());
 }

And what about:

 class A {};
 class B : public A {};
 B    GetB()    { return B(); }
 void fun(A& a) {}
 int main()
 {
    fun(B());
    fun(GetB()); // VC++ 4 warns only about this one.
 }

According to the Apr-95 DWP, sec. 3.10.5, B() and GetB() are rvalues,
and sec. 8.5.3.8 seems to imply that rvalues of class type cannot be
bound to non-const references, except that it goes on to say that "cv1
T1" is (merely) reference-compatible with "cv2 T2", when T2 is a class
type. However, according to 3.10.9:

"An lvalue for an object is necessary in order to modify the object
except that an rvalue of class type can also be used to modify its
referent under certain circumstances. [ Example: a member function
called for an object (9.4) can modify the object. ]"

So, if class A had a (pure virtual) member function modify(),
presumably one could say B().modify() and GetB().modify(). But
presumably, one can't say:

 void fun(A& a)
 {
    a.modify();
 }
 fun(GetB());

Is this correct? I can understand disallowing fun(sin(x)) where fun
takes double&, but why disallow it for class types, especially if
GetB().modify() is allowed? I'm curious because I've heard it claimed
that all the fun() calls I've presented are disallowed under the draft
standard, my compiler inconsistently diagnoses their use, and I find
the description in 8.5.3.8 somewhat ambiguous.

--
Doug Harrison
dHarrison@worldnet.att.net
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]