Reputation: 2308
I have read the book C++ Primer 5th ed. In section Exception Specifications and Pointers, Virtuals, and Copy Control, it says:
That is, if we declare a pointer that has a nonthrowing exception specification, we can use that pointer only to point to similarly qualified functions.
And I also refer to noexcept specifier (since C++11), there is also something similar:
Pointers to non-throwing functions are implicitly convertible (since C++17)can be assigned (until C++17) to pointers to potentially-throwing functions, but not the other way around.
void ft(); // potentially-throwing
void (*fn)() noexcept = ft; // error
When I compile the sample snippet with gcc version 5.4.0 20160609
, there is no error or warning.
But when I compile it with Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x86
, it complains that error C2440: 'initializing': cannot convert from 'void (__cdecl *)(void)' to 'void (__cdecl *)(void) noexcept'
. It seems right behavior.
So I wonder is there something wrong with gcc
compiler?
Upvotes: 0
Views: 155
Reputation: 137425
GCC bug. This is not valid C++11/14 either. N3337 [except.spec]/5, emphasis mine:
If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the exception-specification of the base class virtual function. [ Example: ... — end example ] A similar restriction applies to assignment to and initialization of pointers to functions, pointers to member functions, and references to functions: the target entity shall allow at least the exceptions allowed by the source value in the assignment or initialization.
This is what people mean when they say that pre-C++17 exception specification is a "shadow type system": they are not part of the actual type, but behave in several contexts (initialization, assignment, virtual overrides) as if they are.
Upvotes: 2
Reputation: 33717
Historically, exception specifiers have not been part of the type system:
- Should exception-specifications be part of the type system?
[…]
EWG determined that no action should be taken on this issue.
This is certainly a bit surprising. It is not a loophole in the type system as such because the types are still checked at run time (resulting in abnormal translation if necessary).
However, this issue was resurrected in P0012R1 and merged into the standard with this commit:
commit 6e75f2d588a4b1b0c220eb8eec4b9ad8cb6107f3
Author: Dawn Perchik <[email protected]>
Date: Thu Oct 29 12:11:02 2015 -0700
P0012R1 Make exception specifications be part of the type system, version 5
So it's not in C++14, but will be in C++17. Typically, there is some lag until compilers implement new language features.
Upvotes: 1