Search code examples
c++exceptionc++11inlinenoexcept

C++11 noexcept qualifier and inline methods


Does C++11 give any guarantees about inline functions or methods, when they make calls to other functions declared with the noexcept qualifier?

class My_String { ...

    const char * c_str () const noexcept;
    inline operator const char * () const { return c_str(); }
};

I assume an optimizing compiler would be free to implement the inline method without full EH and stack unwinding, as per the noexcept qualification. I would also expect this for a simple accessor method too:

... inline operator const char * () const { return m_buffer; }

While this example looks trivial, exception guarantees matter when used to implement other classes or functions. Q: Does the C++11 standard address this or should inline methods be marked noexcept? Or is it better to omit noexcept unless required to match a class or function specification?

Edit: To avoid some confusion: Is noexcept implicit for the inline method?


Solution

  • Sorry, no. The only implicit exception-specifications are

    • On destructors.
    • On other implicitly declared or explicitly defaulted special member functions: default constructors, copy and move constructors, and copy and move assignment, when not declared in a class definition, or declared with = default;.
    • On deallocation functions: operator delete and operator delete[].

    [Note that for deallocation functions, an implicit exception-specification is always as if noexcept(true). For all destructors, and for special member functions which are implicitly declared or explicitly defaulted on the first declaration, the implicit exception-specification can be either noexcept(true) or noexcept(false), as determined from the exception-specifications of the corresponding special member functions of any base classes and members of class type.]

    So with either example declaration, noexcept(static_cast<const char*>(std::declval<const MyString>())) must be false. Go ahead and write noexcept where it might matter.

    Of course, as you noted, a compiler optimization is still allowed to notice an inline function can't throw exceptions and simplify exception handling in the caller.