| Last Modified On : | July 2, 2009 3:34 PM PDT |
Rate |
|
Cause:
Overidden virtual functions should have exception-specification at least as restrictive as its own. A caller function might not be able to catch if derived threw an exception that was not advertised in the base class function.
For example:
class Base{
public:
virtual void foo() throw(){} // implies function do not throw any exception
virtual void foo1() throw(int,char){}
virtual void foo2() throw(int){}
};
class Derived:public Base{
public:
void foo() {} // Not ok, Any kind of exception can be thrown. No restriction.
void foo1() throw (int){} //ok, Derived::foo1 is more restrictive than Base::foo1
void foo2() throw(int, char){} // Not ok, Derived::foo is less restrictive than Base::foo
};
Example:
The Intel® C++ compiler emits this diagnostic for following type of code.
class Base{
public:
virtual void f() throw(){}
virtual ~Base() throw(){}
};
class Derived:public Base{
public:
void f() {} // not ok, Can throw any Exception, less restrictive
~Derived() {} // not ok, less restrictive
};
>icl /c /EHsc test.cpp
Intel(R) C++ Compiler Professional for applications running on IA-32, Version 11
.0 Build 20080916 Package ID: w_cproc_p_11.0.061
Copyright (C) 1985-2008 Intel Corporation. All rights reserved.test.cpp
test.cpp(9): warning #809: exception specification for virtual function "Derived
::f" is incompatible with that of overridden function "Base::f"
void f() {} // not ok, Can throw any Exception, less restrictive
^test.cpp(10): warning #809: exception specification for virtual function "Derive
d::~Derived" is incompatible with that of overridden function "Base::~Base"
~Derived() {} // not ok, less restrictive
^
Function like "f()" and "~Derived()" with no exception specification(as in derived) tells compiler that the function can throw any kind of exception. And function with empty exception specification (as in base) tells it will not throw any exception. This leads to base being more restrictive than derived. So compiler warns about such code.
Resolution:
Possible fix for this diagnostic is to change the code so that the derived functions exception specification becomes more restrictive than or compatible with base function.
To get rid of the warning, above given code can be re-written as:
class Base{
public:
virtual void f() throw(){ }
virtual ~Base() throw(){ }
};
class Derived:public Base{
public:
void f() throw() { }
~Derived() throw(){ }
};
English | 中文 | Русский | Français
Grishma Kotecha (Intel)
| ||
Jennifer Jiang (Intel)
|