Bob Hairgrove wrote:
On Fri, 11 Jun 2004 11:24:13 -0700, Andrey Tarasevich
<an**************@hotmail.com> wrote:
red floyd wrote: ...
Am I allowed to pass the anonymous temporary returned by f() to a
function requiring a non-const reference?
No.
I suspect G++ is correct, and VC is (again) braindead.
VC supports this as an extension. The only reason it compiles on VC is
that you have this extension enabled. Disable it and VC will also issue
an error message.
class A
{
public:
A() { }
A(const A&) { }
~A() { }
};
A& operator<<(A& a, const char* p)
{
return a;
}
A f()
{
return A();
}
int main()
{
f() << "Hello";
return 0;
}
You can make this compile by implementing 'operator<<' as a member
function of class 'A'. There's certain asymmetry in C++ behavior when it
comes to things like this...
Doesn't the problem actually stem from the temporary A which is
created from the temporary returned by f() in order to bind to the
non-const reference argument declared by operator<<()?
Yes. That's the immediate reason for the error message, as was already
stated above. However, one way to work around the problem is, once
again, to implement 'operator<<' as a member function of class 'A'.
class A {
public:
...
A& operator<<(const char* p) { return *this; }
};
A f() {
return A();
}
int main() {
f() << "Hello"; // OK, no error
return 0;
}
C++ permits non-constant member function calls on temporary objects. I
can't say whether this is a viable solution in OP's case because all I
have is the above piece of abstract code.
--
Best regards,
Andrey Tarasevich