C ++ exception specification in function pointer

Code:

#include<iostream> using namespace std; void foo() throw(char) {throw 'a';} int main() try { void (*pf)() throw(float); pf = foo; // This should NOT work pf(); } catch(const char& c){cout << "Catched ::> " << c << endl;} 

Why can I pass foo to pf , although the specification of the exception foo is different from what the function pointer pf ? Is this a bug in my compiler?

+4
source share
2 answers

Exception specifications do not participate in a function type. Bugfix: As indicated in another answer, this is really a compiler error. It is well known that most compilers do not work when implementing exception specifications. Also, they are deprecated in C ++ 11. So,

Follow Herb Sutter's tips for exceptions:

Moral # 1: never write an exception specification.

Morality No. 2: except, perhaps, empty, but if I were you, avoid even this.

+9
source

Yes, this is a compiler error. Function pointers must have compatible exception specifiers.

Quote from the standard:

15.4 Exception specifications

(5) ... A similar restriction applies to the assignment and initialization of function pointers, member function pointers, and function references: the target object allows at least the exceptions allowed by the original value in assignment or initialization.

Example:

 class A; void (*pf1)(); // no exception specification void (*pf2)() throw(A); pf1 = pf2; // OK: pf1 is less restrictive pf2 = pf1; // error: pf2 is more restrictive 

Your code compiled with Comeau gives an incompatible exception specifications error:

 Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions "ComeauTest.c", line 9: error: incompatible exception specifications pf=foo; // This should NOT work ^ 

Like many of the other exceptions mentioned, exception specifications are deprecated in the C ++ 11 standard (see Appendix D.4), with the exception of the noexcept specification. So the best practice (and was) is to avoid use .

+5
source

Source: https://habr.com/ru/post/1442800/


All Articles