AlexDan
AlexDan

Reputation: 3331

c++ exception specification in a 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 it is possible to pass foo to pf even though the foo exception specification is different from what the function pointer pf has ? Is this a bug in my compiler?

Upvotes: 4

Views: 1177

Answers (2)

Rost
Rost

Reputation: 9089

Yes, this is compiler bug. Function pointers must have compatible exception specifiers to be assignable.

Quote from standard:

15.4 Exception specifications

(5) ...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.

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 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 
    ^

As many other people mentioned exception specifications are deprecated in C++11 standard (see Annex D.4) except for noexcept specification. So the best practice is (and was) - avoid using it.

Upvotes: 5

Alok Save
Alok Save

Reputation: 206518

Exception specifications don’t participate in a function’s type. Correction: As pointed out in other answer, it is indeed a compiler bug. It is well known fact that most compilers are buggy in implementing exception specifications. Also, they are deprecated in C++11. So,

Follow Herb Sutter's advice with exception specifications:

Moral #1: Never write an exception specification.

Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.

Upvotes: 9

Related Questions