MISRA Discussion Forums

Full Version: Overloaded operators and MISRA C++
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I notice that MISRA C++ does not seem to say much about overloaded operators, and that surprises me a little. I half-expected MISRA to refer to the Boost operators header.

Basically, it works like this:
Code:
//////////////////////////////////
// Boost operator header contains:
namespace boost {
    template
        struct addable1
        {
            friend T operator +( const T& x, const T& y )
                { T t( x ); t += y; return t; }
        };
}

/////////////////////////
// Project code contains:
struct B
    : boost::addable1
{
    B& operator+=( const B& );
};

B f( B &c, B& d )
{
    return c + d; // uses the implicitly-insatntiated friend of
                  // 'boost::addable1', which in turn uses
                  // 'B::operator+='.
}
Compared to the rest of Boost, it's very easy to understand. And it greatly simplifies the construction of a complete set of overloaded operators that behave in a canonical fashion. So I think it could make a lot of sense to introduce an advisory rule that recommends the use of this header.

But note that this whole scheme depends on the friend operator not being instantiated until its first use, and there is a defect report relevant to this: issue 329 (which has been resolved since late 2003). The change given in the DR was not voted into the ISO C++ Working Paper until just after ISO C++2003 released. However, the change to the standard was introduced to match the existing practice of compilers, so very few people (if any) are going to have a problem here. And to find out whether you're one of those few, you only need to feed the above example to your compiler.

Also note, the above example is in violation of rule 14–6–2 because B::operator+= is declared after its use in the friend. But, as I wrote before, I think that rule should probably be removed from MISRA C++.
This is a design issue and is therefore not covered by MISRA C++:2008.