MISRA Discussion Forums
Overloaded operators and MISRA C++ - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2008 rules (https://forum.misra.org.uk/forumdisplay.php?fid=19)
+---- Forum: 6.7 Declarations (C++) (https://forum.misra.org.uk/forumdisplay.php?fid=136)
+---- Thread: Overloaded operators and MISRA C++ (/showthread.php?tid=550)



Overloaded operators and MISRA C++ - James Widman - 10-07-2008

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++.


Re: Overloaded operators and MISRA C++ - misra cpp - 05-10-2015

This is a design issue and is therefore not covered by MISRA C++:2008.