Code below fails with "no match for operator>>", although works in msvc. If I'm doing something wrong or there is simple workaround please let me know. scott@stg.net. #include <stdio.h> class FooBar { public: FooBar(const char *s) { printf("Constructed: %s\n",s); } void Accept(const char *s) { printf("Passed: %s\n",s); } }; FooBar& operator>> (const char *s,FooBar& dest) { dest.Accept(s); return(dest); } int main(int argc,char **argv) { FooBar test1("one"); "A">>test1; "B">>FooBar("two"); }
You cannot bind a rvalue to a reference, only a constant reference or to a non reference.
Okay, so if I change: FooBar& operator>> (const char *s,FooBar& dest) to FooBar operator>> (const char *s,FooBar dest) It now compiles on both msvc and g++, but required functionality (operation affecting existing object, not making new copy of it) is lost. Is there some reason that using a reference to rvalue in operator>> is disallowed in gcc and not msvc? If so, why doesn't it fail in the A>>object; instance where the object has already been instantiated separately?
For clarification, this code compiles & runs in gcc & msvc: FooBar test1("one"); "A">>test1; And this code compiles & runs fine in msvc, but gives compile error in gcc: "B">>FooBar("two"); Since it's the same class, why should there be any difference in matching operator>> depending on how it's instantiated? The sample code is a distillation (demonstration) from a larger code base for convenience of exploring this issue.
Because the result of FooBar("two") is an rvalue, but test1 is an lvalue.