虚函数的异常规范与重写函数的异常规范不兼容

问题描述 投票:0回答:1

我用intel的

icpc
(版本14.0.1,使用
-std=c++11
)收到此错误消息,而clang(版本3.4)和gcc(版本4.8.1)都很高兴。典型的违规代码是:

#include <vector>
namespace test {
  struct A
  {
    virtual bool foo(std::size_t) const = 0;
    virtual ~A() = default;
  };

  struct B
  : A
  {
    const std::vector<double> V;
    const double X;
    bool foo(std::size_t i) const { return V.at(i) > X; }
    virtual bool bar(std::size_t i) const { return V.at(i) < X; }
    B(double x, std::vector<double> const &v)
      : V(v), X(x) {}
    ~B() = default;
  };
}

由于

test::A
是抽象的,最好有一个虚拟析构函数。然而, icpc 抱怨(编译错误不是警告)关于

虚函数“test::B::~B”的异常规范是 与重写函数“test::A::~A”不兼容

我认为这一切都是英特尔编译器的一些错误。正确吗?

PS。我注意到一个相关的问题,是在 C++11 之前提出的。当

throw
被弃用(并被
noexcept
取代)时,我真的很担心 C++11。

c++ exception inheritance c++11 virtual
1个回答
0
投票

此错误消息表明您的类的析构函数与基类的析构函数具有不同的异常规范。编译器隐式声明派生类的析构函数,并且存在不兼容性。

要解决此问题,请使用适当的异常规范为您的类显式定义析构函数,以匹配基类的析构函数。最有可能的是,基类析构函数被声明为

noexcept

// ...

class DerivedClass : public BaseClass {
public:
    // Explicitly define a noexcept destructor
    virtual ~DerivedClass() noexcept = default;

    // ... (rest of your class definition)
};
© www.soinside.com 2019 - 2024. All rights reserved.