覆盖函数的异常规范比基本版本宽松 [英] exception specification of overriding function is more lax than base version

查看:615
本文介绍了覆盖函数的异常规范比基本版本宽松的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自定义一个Exception类,这是代码:

I want to custom an Exception class, here's the code:

class TestException : std::exception{
  public:
  const char *what() const override {
    return "TestException";
  }
};

我用过Clion,IDE对函数警告我( )覆盖功能的例外规范比基本版本更宽松

I used Clion and the IDE give me a warning on the function what():exception specification of overriding function is more lax than base version

我使用gcc构建代码,没有警告发出。
我使用了c ++ 14,gcc 6.5.0

But if I build the code with gcc, there's no warning came out. I used c++ 14, gcc 6.5.0

有人可以帮忙解释一下警告的意思吗?

Can anybody help to explain what does the warning mean and can I just ignore it?

推荐答案

std :: exception 中的什么 虚拟函数和 virtual 函数不能具有比其在基类中覆盖的函数更宽松的 exception规范

what from std::exception is a virtual function and a virtual function in a derived class cannot have a laxer exception specification than the function it overrides in the base class.

在标准的异常说明部分中对此进行了提及。

This is mentioned in the section on "Exception specifications" in the standard.


18.4异常规范[except.spec]

...

4.如果虚拟函数具有非抛出异常规范,则所有声明覆盖任何派生类中的虚函数的任何函数(包括定义)都应具有非抛出异常规范,除非将覆盖函数定义为已删除。

18.4 Exception specifications [except.spec]
...
4. If a virtual function has a non-throwing exception specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall have a non-throwing exception specification, unless the overriding function is defined as deleted.

给出的示例(与问题代码有点相似)也对此进行了说明。

And the example given (which is somewhat similar to the code in the question) illustrates this as well.

struct B 
{ 
  virtual void f() noexcept; 
  virtual void g(); 
  virtual void h() noexcept = delete; 
};
struct D: B 
{ 
  void f(); // ill-formed 
  void g() noexcept; // OK 
  void h() = delete; // OK 
}; 




D :: f <的声明/ code>的格式错误,因为它具有可能抛出的异常指定,而 B :: f 具有没有抛出的异常指定。

The declaration of D::f is ill-formed because it has a potentially-throwing exception specification, whereas B::f has a non-throwing exception specification.

解决方案是更改代码,例如:

The solution is to change your code like:

class TestException : std::exception{
  public:
  const char *what() const noexcept override {
    return "TestException";
  }
};

请参见编译在这里。

这篇关于覆盖函数的异常规范比基本版本宽松的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆