c++functionthrownoexcept

Should I use noexcept specifier and noexcept operator in most functions in C++?


I'm still new to the C++ programming language, and I'm trying to learn new things.

I'm implementing a very very basic iterator/reverse_iterator classes and other standard library containers.

I see in most standard library implementations like GCC, MS, and others that they use the noexcept specifier and noexcept operator in the majority of their functions to test if they throw or not.

This is one example:

_GLIBCXX17_CONSTEXPR
        reverse_iterator(const reverse_iterator<_Iter>& __x)
    _GLIBCXX_NOEXCEPT_IF(noexcept(_Iterator(__x.current)))
    : current(__x.current)
    { }

_GLIBCXX_NODISCARD
      _GLIBCXX17_CONSTEXPR iterator_type
      base() const
      _GLIBCXX_NOEXCEPT_IF(noexcept(_Iterator(current)))
      { return current; }

But, there are parts where they don't use them, like this:

template<typename _Iterator>
    _GLIBCXX_NODISCARD
    inline _GLIBCXX17_CONSTEXPR bool
    operator==(const reverse_iterator<_Iterator>& __x,
           const reverse_iterator<_Iterator>& __y)
    { return __x.base() == __y.base(); }

I know that if a function is marked as noexcept, the compiler can perform some optimizations, and also know that only needs to be used where you know the function (or calls to other functions inside) cannot throw exceptions.

As until I understand, here is used because we're working with templates, and we're testing if the type does or doesn't throw (please correct me if I'm wrong).

So, in what situations do I need to test for no-throwing with noexcept specifier and noexcept operator in functions?

And, from the example above with the comparison operator, why don't they use noexcept?

Can I mark those comparison operators noexcept or test if they are noexcept?


Solution

  • I did some research on several websites and found great information that expanded my knowledge in the noexcept usage.

    After reading the Andrzej's C++ blog. Using noexcept I understood how does noexcept work better and when to use it and when to avoid it.

    From the examples that I introduced in my question, I wanted to know why, in this particular case, the operator== is not using noexcept if is well known that mark a function/constructor as noexcept the compiler can perform some optimization and I ended with the conclusion that there is no performance gain if I use it in that particular function.

    In other words, the operator== don't need the noexcept specification because no performance gain is used for the code itself because there are no move-like operations involved or other kind of no-throw exceptions guarantees that are needed. And finally, the operator== is marked as inline constexpr that is going to inline the function where used, so that is a performance gain for that particular code.