JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc
C and C++


LANG.FUNCS.SOMF : Symmetrical Operator Member Function

Summary

FIXME

Properties

Class Name Symmetrical Operator Member Function
Significance style
Mnemonic LANG.FUNCS.SOMF
Categories
MisraC++2023 MisraC++2023:16.6.1 Symmetrical operators should only be implemented as non-member functions
Availability Available for C++ only (not C).
Enabling Checks for this warning class are disabled by default. To enable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += allow class="Symmetrical Operator Member Function"

Example

class Bad {
public:
    Bad(int x = 0) : i(x) {}
    int get(void) const { return i; }
    Bad operator +(const Bad &o)  const // "Symmetrical Operator Member Function" warning issued here
    {
        return Bad(i + o.i);
    }
    Bad operator +(int x) const         // "Symmetrical Operator Member Function" warning issued here
    {
        return Bad(i + x);
    }
    Bad & operator +=(const Bad &o)     // Not symmetrical; rule does not apply
    {
        i += o.i;
        return *this;
    }
private:
    int i;    
};

Bad operator *(const Bad l, const Bad r)        // OK : not member
{
    return Bad(l.get() * r.get());
}

class Good {
public:
    Good(int x = 0) : i(x) {}
    int get(void) const { return i; }
    friend Good operator+(const Good &l, const Good &r);// OK : friend
    friend Good operator+(const Good &l, int r)         // OK : hidden friend
    {
        return Good(l.i + r);
    }
private:
    int i;
};

Good operator +(const Good &l, const Good &r)
{
    return Good(l.i + r.i);
}

Good operator *(const Good l, const Good r)     // OK : not member
{
    return Good(l.get() * r.get());
}

void symmetrical_operator_member_function(void)
{
    Bad b1(21);
    Bad b2(b1 + 1);
    Bad b3(b1 + b2);
    Good g1(21);
    Good g2(g1 + 1);

    //(void)(1 + b1);   // Would fail to compile
    (void)(b1 * 4);
    (void)(4 * b2);
    b3 += 2;
    (void)(1 + g1);     // Compiles just fine.
    (void)(g1 * 4);
    (void)(4 * g2);
}

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.

 

To report problems with this documentation, please visit https://support.codesecure.com/.