Why is T() = T() allowed?

Posted by Rimo on Stack Overflow See other posts from Stack Overflow or by Rimo
Published on 2010-05-28T04:26:41Z Indexed on 2010/05/28 7:02 UTC
Read the original article Hit count: 184

Filed under:
|
|

I believe the expression T() creates an rvalue (by the Standard). However, the following code compiles (at least on gcc4.0):

class T {};

int main()
{
    T() = T();
}

I know technically this is possible because member functions can be invoked on temporaries and the above is just invoking the operator= on the rvalue temporary created from the first T().

But conceptually this is like assigning a new value to an rvalue. Is there a good reason why this is allowed?

Edit: The reason I find this odd is it's strictly forbidden on built-in types yet allowed on user-defined types. For example, int(2) = int(3) won't compile because that is an "invalid lvalue in assignment".

So I guess the real question is, was this somewhat inconsistent behavior built into the language for a reason? Or is it there for some historical reason? (E.g it would be conceptually more sound to allow only const member functions to be invoked on rvalue expressions, but that cannot be done because that might break some existing code.)

© Stack Overflow or respective owner

Related posts about c++

Related posts about operator-overloading