首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >c++标准关于在缺省析构函数中丢失抛出说明符的规定

c++标准关于在缺省析构函数中丢失抛出说明符的规定
EN

Stack Overflow用户
提问于 2012-03-09 22:14:46
回答 2查看 8.2K关注 0票数 19

三个不同的编译器显示了编译此代码的三种不同行为:

代码语言:javascript
复制
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 (没有错误或警告)

代码语言:javascript
复制
class exception {
public:
  exception () throw();
  exception (const exception&) throw();
  exception& operator= (const exception&) throw();
  virtual ~exception() throw();
  virtual const char* what() const throw();
}

我知道问题是什么,以及我如何解决它:

代码语言:javascript
复制
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中运行了另一个小测试,我发现了一些让我非常惊讶的东西:

代码语言:javascript
复制
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完全忽略了异常规范。

代码语言:javascript
复制
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呢?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9635464

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档