Search code examples
c++visual-studio-2017inline

Overloading == and !=, but program only use the former


My code look like this

template <typename T>
class FArray
{
/* ... */
    inline bool operator == (const FArray& b) const
    {
        return std::equal(begin(),end(),b.begin());
    }
    inline bool operator != (const FArray& b) const
    {
        return !(*this == b);
    }
};

Then I have some unit tests, and I'm testing equality and inequality

FArray<double> a, b, c;
/* ... */
ASSERT_TRUE(a == b)
ASSERT_TRUE(a != c)

The second assert doesn't use the overloaded operator !=, it uses only == and I think returns its negation (I added a breakpoint in the overloaded function, my program doesn't go through it). But if I don't overload one or the other, I can't compile. Is it standard behavior? I couldn't find any related info about this online.

I'm using Visual Studio 2017 15.5.6, with Visual C++ 2017 - 00369-60000-00001-AA639.


Solution

  • It uses operator== because it is invoked in operator!=.

    It uses only operator== because operator!= might be inlined,

    instead of executing the function call CPU instruction to transfer control to the function body, a copy of the function body is executed without generating the call.

    Then you won't see the invocation if it's the case.

    It's also worth noting that the function is inlined or not depends on the compiler; it's not guaranteed.

    Since this meaning of the keyword inline is non-binding, compilers are free to use inline substitution for any function that's not marked inline, and are free to generate function calls to any function marked inline.