Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this function marked as noexcept, but can throw?

This is a function from < mutex > (MSVSC)

Part of conditional_variable:

void notify_one() noexcept { // wake up one waiter
        _Check_C_return(_Cnd_signal(_Mycnd()));
    }

It's marked as noexcept, but _Check_C_return can throw(from < xthreads.h >):

inline int _Check_C_return(int _Res) { // throw exception on failure
    if (_Res != _Thrd_success) {
        _Throw_C_error(_Res);
    }

    return _Res;
}

So, I've got 2 questions:

  1. Why is it marked as noexcept?
  2. If it throws in my program, is it my fault?
like image 664
mylibh Avatar asked Mar 11 '20 01:03

mylibh


2 Answers

notify_one is required to be noexcept by the language.

If the internal implementation of notify_one tries to throw, then this is a bug in the library implementation. If the exception is thrown, std::terminate is required to be called.

However, looking at the headers and source code provided with the compiler, it appears (if I'm reading thru all those macros, typedefs, and inline methods correctly) that the value returned from _Mycnd() will be a pointer to an internal class member, which will never be NULL. The condition will then always be true, so that nothing is ever thrown.

like image 89
1201ProgramAlarm Avatar answered Sep 28 '22 20:09

1201ProgramAlarm


notify_one is marked as noexcept because the Standard specifies that it must be.

If an uncaught exception is thrown inside a noexcept function , then std::terminate is called, which aborts the program (and the stack may or may not be unwound). I can't really answer whether the exception is "your fault" or not, this would depend on details of the library implementation and analyzing under what conditions a throw statement might be executed.

like image 44
M.M Avatar answered Sep 28 '22 20:09

M.M