【问题标题】:Are inheriting constructors noexcept(true) by default?默认情况下继承构造函数 noexcept(true) 吗?
【发布时间】:2016-06-17 12:00:02
【问题描述】:

Here我发现:

默认情况下,继承构造函数 [...] 都是 noexcept(true),除非它们需要调用 noexcept(false) 的函数,在这种情况下,这些函数是 noexcept(false)。

这是否意味着在下面的示例中,继承的构造函数是noexcept(true),即使它已在基类中明确定义为noexcept(false),或者它本身被视为一个没有例外的函数(false) 被调用?

struct Base {
    Base() noexcept(false) { }
};

struct Derived: public Base {
    using Base::Base;
};

int main() {
    Derived d;
}

【问题讨论】:

    标签: c++ c++11 constructor noexcept inheriting-constructors


    【解决方案1】:

    继承的构造函数也将是noexcept(false),因为正如您引用的那样,继承的构造函数默认为noexcept(true)

    除非他们需要调用 noexcept(false) 的函数

    Derived 构造函数运行时,它也会调用Base 构造函数,即noexcept(false),因此,Derived 构造函数也将是noexcept(false)

    以下内容证明了这一点。

    #include <iostream>
    
    struct Base {
      Base() noexcept(false) { }
    };
    
    struct Derived: public Base {
      using Base::Base;
    };
    
    int main() {
      std::cout << noexcept(Derived());
    }
    

    输出 0。

    【讨论】:

    • 我认为该网站上的那部分文档还很不清楚......无论如何,这是有道理的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2017-10-04
    • 2015-07-09
    • 2011-05-20
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多