DeMarcus <use_my_alias_here@hotmail.com> writes:
If you are going to allow use of your `stream' utilizing temporaries
formed by A(), then you are essentially breaking the `model'. If you
implement it as:
A& operator<<(A&&, const B&)
then you're going to be running into a few problems. Firstly, with this
you are returning a reference to a temporary that has no existence after
the call.
Yes, but as far as I remember, the temporary should live the whole
full-expression, i.e. the whole chaining.
I would need to look into the detail as I'm a little hazy on whether
that would be the case or not. However, there are other issues here.
One is that chaining is not actually even possible with the above
signature, since the return of an lvalue ref prevents the second
invocation in the chain since the argument is not now an rvalue any
more.
14:33:46 Paul Bibbings@JIJOU
/cygdrive/d/CPPProjects/CLCPP/consistent_resolution $cat
ret_by_ref.cpp
// file: ret_by_ref.cpp
#include <iostream>
class A { };
class B { };
A& operator<<(A&& a, const B&)
{
std::cout << "op<<";
return a;
}
int main()
{
B b;
A() << b; // line 17: OK
A() << b << b; // line 18: error
}
14:33:51 Paul Bibbings@JIJOU
/cygdrive/d/CPPProjects/CLCPP/consistent_resolution
$i686-pc-cygwin-gcc-4.5.0 -std=c++0x -c ret_by_ref.cpp
ret_by_ref.cpp: In function ??int main()??:
ret_by_ref.cpp:18:16: error: cannot bind ??A?? lvalue to ??A&&??
ret_by_ref.cpp:8:4: error: initializing argument 1 of ??A&
operator<<(A&&, const B&)??
<snip>
But if implement it like this:
A&& operator<<( A&& a, const B& b )
{
return a << "B";
}
What compiler are you using? I would expect this not to compile since,
within the body of the function, a behaves as an lvalue and hence in the
return should not bind on A&&. The following might work, but then you
have the move semantics that your referred to earlier:
A&& operator<<(A&& a, const B& b) // untested
{
a << "B"; // #1
return std::move(a);
}
a.set(4711) where set() just set some variable in a. But there were no
problems compiling either of them. I agree it's a bit tricky to