Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Overloaded operators and MISRA C++
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:
// Boost operator header contains:
namespace boost {
        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++.
<r>James Widman<br/>
-- <br/>
Gimpel Software<br/>
<URL url=""></URL></r>
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

Forum Jump:

Users browsing this thread: 1 Guest(s)