3

If I have something like this

struct A{
    int x;
    constexpr A() : x(0){}
    constexpr void set(){ x = 0; }
    constexpr bool check()const{ return x == 5; }
};

Does writing set and check as noexcept make any good/difference?

To generalize: do I need to write functions, that only perform operations on integral types, as noexcept ?

Hrisip
  • 900
  • 4
  • 13
  • Depends on how you intend to use your data structure and those functions. Declaring those function `noexcept` makes life easier if they are called from a large, complicated function that is also specified as `noexcept`. If they aren't called from such a function, it's up to you. – Peter Dec 01 '19 at 08:16
  • @Peter, I thought, since all of them are going to be inlined, the compiler will check the operations inside the function for `noexcept`, because it will do so anyway; and in case with operations on integral types they will be deduced `noexcept`, making my `noexcept` redundant – Hrisip Dec 01 '19 at 08:37
  • You're making some grand assumptions about what analysis a compiler will do. – Peter Dec 01 '19 at 08:51
  • I always regarded this keyword as more of a hint to the human maintaners. – Hitobat Dec 01 '19 at 09:01

1 Answers1

3

noexcept serves two purposes: it describes an interface, and it improves performance. The first is important even when the function is trivial, in that it documents that (in all compatible versions) it will stay non-throwing even if the implementation becomes more complex (and perhaps stops being inline). That property is important for clients that want to write exception-safe code (and changing it can silently break them).

The second has two components: while direct code generation may be unaffected when the body is simple and available, the library behavior associated with a type depends only on its declaration (which is a good thing, given the interface idea). Libraries tend to check the potential for throwing from only a few functions (especially the special member functions), so that’s unlikely to matter in this case, but do note that the space of “special” functions grows over time (e.g., swap, operator==).

The conclusion is that you should write noexcept when it’s important—either to your human readers or to your analyzing libraries.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76