This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Temporaries



> I'm attempting to port some code that has the following definitions:
> --------------------- cut here ---------------
> class Set {
> 	public:
> 	Set &operator |= ( Set & );
> 	Set &operator | ( Set & );
> };
> Set &Set::operator | ( Set &rhs ) {
> 	return Set(rhs)|=lhs;
> };
> --------------------- cut here ---------------

This is not legal C++.

> Under visual c++, this is fine,

Actually it may not be fine under C++ ("compiles" != "fine").  That is,
the code in question is likely to have strange bugs, as you are trying to
create a reference to a temporary which is on a portion of the stack that
is popped.

> but under gcc it is an error (not a warning),
> because the non-const reference parameter of operator |= is being initialized
> with an rvalue of type 'String'.
> 
> I always thought that an explicit constructor invocation yielded an lvalue.

No, it produces a temporary.

> but in some cases, like the one above, it would be
> quite useful, saving from the longer:
> {
> 	Set temp(lhs);
> 	temp |= rhs;
> 	return lhs;
> };

I write such code all the time, but I make the return type of operator|
Set, not Set&, and it works fine.  I'll bet that if you do the same you
can get the code to work.

> What, if anything, does the standard say on this subject?  I couldn't find
> anything in Stroustrup (3rd) to clarify.

The standard bans it.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]