Overloaded operators and MISRA C++

Moderators: david ward, misra cpp

Post Reply
James Widman
Posts: 9
Joined: Fri Jun 20, 2008 9:17 pm
Company: Gimpel Software

Overloaded operators and MISRA C++

Post by James Widman » Thu Jul 10, 2008 6:43 pm

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: Select all

//////////////////////////////////
// Boost operator header contains:
namespace boost { 
    template <class T>
        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>
{
    B& operator+=( const B& );
};

B f( B &c, B& d )
{
    return c + d; // uses the implicitly-insatntiated friend of
                  // 'boost::addable1<B>', 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++.
James Widman
--
Gimpel Software
http://gimpel.com

misra cpp
Posts: 148
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Overloaded operators and MISRA C++

Post by misra cpp » Mon Oct 05, 2015 3:06 pm

This is a design issue and is therefore not covered by MISRA C++:2008.
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.7 Declarations (C++)”