Hrisip
Hrisip

Reputation: 920

Is it necessary to write noexcept for a function that does almost nothing?

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 ?

Upvotes: 3

Views: 118

Answers (1)

Davis Herring
Davis Herring

Reputation: 39818

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.

Upvotes: 3

Related Questions