Another C++ ugly feature

While telling friends about some of the nice syntactic amibiguities of C++, I noticed that the following code actually compiles on two compilers I trust, HP’s aCC (based on the highly respected EDG C++ front end), and g++ 3.4.5.

struct ripoux {
    ripoux & operator= (const ripoux &other) { return *this; }
    operator bool() { return true; }
};

ripoux operator *(const ripoux &a, const ripoux &b) { return b; }

int main()
{
    ripoux x, y, z;
    if (x * y = z)
        return 42;
    return 0;
}

What I find particularly distasteful with this code is that operator= is a standard assignment operator, as most C++ programmers would write it. Yet this operator can write into a so-called r-value, the result of a function call (in that case, a call to operator *), which is not returned by reference or anything that would suggest that it’s an l-value. To me, this means that the original meaning of l-value as on the left of an assignment is completely lost in C++…

I had two compilers accepting the code, and I could not find anything in the C++ standard actually forbidding it. So I checked with my personal C++ guru, Daveed Vandevoorde, and he confirmed that this was intended behavior. Another disappointment with C++, I guess.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s