Bug 37043 - fails to find operator match when constructing object on the fly
Summary: fails to find operator match when constructing object on the fly
Status: RESOLVED INVALID
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.1.2
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2008-08-06 22:10 UTC by Scott Griepentrog
Modified: 2008-08-07 15:19 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Scott Griepentrog 2008-08-06 22:10:22 UTC
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");
}
Comment 1 Andrew Pinski 2008-08-06 22:13:31 UTC
You cannot bind a rvalue to a reference, only a constant reference or to a non reference.
Comment 2 Scott Griepentrog 2008-08-07 13:31:11 UTC
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?
Comment 3 Scott Griepentrog 2008-08-07 13:53:54 UTC
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.
Comment 4 Andreas Schwab 2008-08-07 15:19:58 UTC
Because the result of FooBar("two") is an rvalue, but test1 is an lvalue.