Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat the c++ standard says about loosing throw specifier in default destructor
    text
    copied!<p>Three different compilers show three different behaviours compiling this code:</p> <pre><code>class MyException : public std::exception { public: MyException(std::string str) : m_str(str) {} virtual const char * what() const throw () {return m_str.c_str(); } protected: std::string m_str; }; </code></pre> <p>Sun C++ 5.8 Patch 121017-22 2010/09/29: <strong>Warning</strong> Function MyException::~MyException() can throw only the exceptions thrown by the function std::exception::~exception() it overrides</p> <p>g++ 3.4.3: <strong>Error</strong> looser throw specifier for `virtual MyException::~MyException()'</p> <p>Visual Studio 2005: <strong>It is very happy</strong> (neither error or warning)</p> <pre><code>class exception { public: exception () throw(); exception (const exception&amp;) throw(); exception&amp; operator= (const exception&amp;) throw(); virtual ~exception() throw(); virtual const char* what() const throw(); } </code></pre> <p>I know what the problem is and how I can fix it:</p> <pre><code>class MyException : public std::exception { public: MyException(std::string str) : m_str(str) {} virtual const char * what() const throw () {return m_str.c_str(); } ~MyException() throw() {} &lt;------------ now it is fine! protected: std::string m_str; }; </code></pre> <p><strong>However I am wondering what the standard says in specific situation.</strong></p> <p>I ran another small test in Visual Studio 2005 and I have found something that really surprise me:</p> <pre><code>struct Base { virtual int foo() const throw() { return 5; } }; struct Derived : public Base { int foo() const { return 6; } }; int main() { Base* b = new Derived; std::cout &lt;&lt; b-&gt;foo() &lt;&lt; std::endl; //&lt;-- this line print 6!!! delete b; } </code></pre> <p>The signature of the two functions are different. How can this work? It seems that visual studio 2005 completely ignore the exception specification.</p> <pre><code>struct Base { virtual int foo() const throw() { return 5; } }; struct Derived : public Base { int foo() { return 6; } // I have removed the const keyword // and the signature has changed }; int main() { Base* b = new Derived; std::cout &lt;&lt; b-&gt;foo() &lt;&lt; std::endl; // &lt;-- this line print 5 delete b; } </code></pre> <p><strong>Is this c++ standard? Is there any magic flag to set?</strong></p> <p><strong>What about VS2008 and VS2010?</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload