如何检测一个具有抛出析构函数的构造函数是否为noexcept

4
以下代码在大多数编译器上都无法编译成功:
#include <type_traits>

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

static_assert(std::is_nothrow_default_constructible_v<Foo>);

CppReference同样说明,这在编译器实现中很常见,但没有提供替代方法。如何在析构函数不影响结果的情况下测试一个构造函数是否为noexcept?

1个回答

2
LWG问题2116中所述,链接自您提供的cppreference页面,这并不是一个bug,而是预期的行为。
正如该问题中也提到的,可以使用非抛出的placement-new来测试仅构造函数的异常规范,它只构造对象,而不会销毁。
static_assert(noexcept(::new(std::nothrow) Foo()));

这需要包含<new>,用于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> { };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接