c++g++c++17noexceptgcc7

Handling gcc's noexcept-type warning


Consider this example, from bug 80985:

template <class Func>
void call(Func f)
{
    f();
}

void func() noexcept { }

int main()
{
    call(func);
}

Compiling this with all warnings enabled, as you do, yields:

$ g++ -std=c++14 -Wall foo.cxx 
foo.cxx:2:6: warning: mangled name for ‘void call(Func) [with Func = void (*)() noexcept]’ will change in C++17 because the exception specification is part of a function type [-Wnoexcept-type]
 void call(Func f)
      ^~~~

What exactly am I supposed to do with this warning? What is the fix?


Solution

  • There's several things you can do about the warning message.

    Disable it with -Wno-noexcept-type. In many projects the warning message is unhelpful because there's no chance the resulting object will be linked with an another object that expects it to use GCC's C++17 name mangling. If you're not compiling with different -std= settings and you're not building a static or shared library where the offending function is part of its public interface then the warning message can safely disabled.

    Compile all your code with -std=c++17. The warning message will go away as the function will use the new mangled name.

    Make the function static. Since the function can no longer be referenced by another object file using a different mangling for the function the warning message will not be displayed. The function definition will have to be included in all compilation units that use it, but for template functions like in your example this is common anyways. Also this won't work for member functions were static means something else.

    When calling a function template specify the template parameter explicitly giving a compatible function pointer type that doesn't have the exception specification. For example call<void (*)()>(func). You should also be able to use cast to do this as well, but GCC 7.2.0 still generates a warning even though using -std=c++17 doesn't change the mangling.

    When the function isn't a template don't use noexcept with any function pointer types used in the function's type. This and the last point rely on the fact that only non-throwing function pointer types result in naming mangling changes and that non-throwing function pointers can be assigned (C++11) or implicitly converted (C++17) to possibly throwing function pointers.