noexcept specifying conditions under which function does not throw

1.3k Views Asked by At

I am having some trouble wrapping my head around noexcept.

template <int SIZE>
int pop(int idx) noexcept(noexcept(SIZE > 0)) // this is what I dont understand
{
  if (idx <= 0)
    throw std::out_of_range("My array doesnt go that high");
  return idx;
}

This is just a simple function, but you see how it only throws an exception when idx <= 0, I dont understand. So in my specification, noexcept(idx > 0), I am trying to tell the compilier this function ONLY throws no exceptions if idx > 0. Am I doing this right?

Any help is appreciated, I hope I am explaining it right. Just some simple explanation would be great.

1

There are 1 best solutions below

5
On BEST ANSWER

Actually the noexept specification expects a constant expression, not a runtime expression. You have used the noexcept specificatiom together with the noexcept operator. noexcept(idx >0) returns true as comparing two integers does not throw, and you are using that true as the argument to the noexcept specification telling the compiler your function never throws. The declaration

int pop(int idx) noexcept(noexcept(idx > 0))

says this function does not throw as long as idx > 0 does not throw, which is always the case for an int.

Update: Now you've changed the code in the question so that idx is a non-type template argument, however the same reasoning applies. Comparing ints never throws.

What you seem to be trying to do cannot be done in C++. That is, specify whether a function throws or not based on its runtime arguments.