【问题标题】:Protected noexcept constructor doesn't seem noexcept from derived class. Why?受保护的 noexcept 构造函数似乎不是来自派生类的 noexcept 。为什么?
【发布时间】:2019-03-07 23:57:20
【问题描述】:

这里是来源:

#include <type_traits>
#include <utility>

class A {
protected: 
//public: // if public, it's fine. (?)
    A()noexcept{}
    A(A&&) noexcept{}
};

class B : public A {
    static_assert(std::is_nothrow_constructible<A>::value,"err1"); // ! err1
    static_assert(std::is_nothrow_move_constructible<A>::value,"err2"); // ! err2

public:
    B()noexcept(std::is_nothrow_constructible<A>::value):A(){}
    B(B&& o)noexcept(std::is_nothrow_move_constructible<A>::value):A(std::move(o)){}
};

int main(){
    static_assert(std::is_nothrow_constructible<B>::value,"err3"); // ! err3
    static_assert(std::is_nothrow_move_constructible<B>::value,"err4"); // ! err4
    return 0;
}

编译失败,出现 err1、err2、err3 和 err4。 但是,如果我公开了 A 类的构造函数,它就可以工作。 为什么?

(Clang 6.0,7.0; gcc 8.x; ...)

【问题讨论】:

  • 我认为这是因为受保护的构造函数在类之外是不可构造的

标签: c++ noexcept


【解决方案1】:

std::is_nothrow_constructiblestd::is_nothrow_move_constructible 检查是否表达式

T obj(std::declval<Args>()...);

格式良好。由于它在类的上下文之外进行此检查,因此考虑了成员访问。由于您的构造函数受到保护,因此表达式不合法,并且特征返回 false。

【讨论】:

    猜你喜欢
    • 2016-12-10
    • 2019-12-09
    • 2021-04-07
    • 2020-05-08
    • 2012-12-07
    • 2016-08-10
    • 2021-10-05
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多