覆盖函数的异常规范比基本版本宽松

覆盖函数的异常规范比基本版本宽松

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

问题描述

我想自定义一个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?

推荐答案

虚拟函数和 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.

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

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
};



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

The solution is to change your code like:

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

请参见在这里。

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

08-22 15:27