三个不同的编译器显示了编译此代码的三种不同行为:
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;
};
Sun exception 5.8修补程序121017-22 2010/09/29:警告函数MyException::~MyException()只能抛出它所覆盖的std::exception::~exception()函数引发的异常
g++ 3.4.3:Error ` `virtual::~MyException()‘的松散抛出说明符
Visual Studio2005:It is very happy (没有错误或警告)
class exception {
public:
exception () throw();
exception (const exception&) throw();
exception& operator= (const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw();
}
我知道问题是什么,以及我如何解决它:
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() {} <------------ now it is fine!
protected:
std::string m_str;
};
然而,我想知道在特定情况下标准是怎么说的。
我在Visual Studio2005中运行了另一个小测试,我发现了一些让我非常惊讶的东西:
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 << b->foo() << std::endl; //<-- this line print 6!!!
delete b;
}
这两个函数的签名不同。这是如何工作的呢?似乎visual studio 2005完全忽略了异常规范。
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 << b->foo() << std::endl; // <-- this line print 5
delete b;
}
这是c++标准吗?有什么神奇的标志可以设置吗?
VS2008和VS2010呢?
https://stackoverflow.com/questions/9635464
复制相似问题