3

以下代码将无法在大多数编译器上编译:

#include <type_traits>

class Foo
{
    public:
    Foo() noexcept {}
    ~Foo() noexcept(false) {}
};

static_assert(std::is_nothrow_default_constructible_v<Foo>);

CppReference 还指出这在编译器实现中很常见,但没有提供替代方案。如何在没有析构函数影响结果的情况下测试构造函数是否为 noexcept?

4

1 回答 1

2

LWG issue 2116中所述,从您链接的 cppreference 页面链接,这不是错误,而是预期的行为。

正如该问题中还提到的,可以使用仅构造但不破坏对象的非抛出placement-new 来测试仅构造函数的异常规范:

static_assert(noexcept(::new(std::nothrow) Foo()));

这需要包括<new>for std::nothrow

这是该特征的粗略实现:

template<class T, class = void>
struct is_nothrow_default_constructible
: std::bool_constant<false> { };

template<class T>
struct is_nothrow_default_constructible<T,
    std::enable_if_t<noexcept(::new(std::nothrow) T())>>
: std::bool_constant<true> { };
于 2019-11-16T18:51:45.160 回答