如何检测构造函数是否与抛出的析构函数无关
How to detect if a contructor is noexcept with a throwing destructor
以下代码将无法在大多数编译器上编译:
#include <type_traits>
class Foo
{
public:
Foo() noexcept {}
~Foo() noexcept(false) {}
};
static_assert(std::is_nothrow_default_constructible_v<Foo>);
CppReference还指出,这在编译器实现中很常见,但没有提供替代方案。如果析构函数不影响结果,我如何测试构造函数是否为noexcept?
正如LWG第2116期中所提到的,从您链接的cppreference页面链接,这不是一个bug,而是预期行为。
正如该问题中所提到的,可以使用非抛出放置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> { };
相关文章:
- 析构函数是否会自动调用 delete[] C++?
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- 文件流析构函数是否可以在C++中引发异常?
- 构造函数是否unique_ptr初始化原始指针unique_ptr析构函数是否也删除关联的原始指针?
- 析构函数是否可以在 const 对象上调用非 const 函数
- cpp 中的析构函数是否自动调用?即使析构函数没有提及非动态变量,它们也会被删除吗?
- 析构函数是否可以不调用特定字段的析构函数
- 动态分配(堆上)的对象的析构函数是否会在返回函数中自动调用
- 当类中存在虚函数时,隐式生成的析构函数是否也是虚拟的
- C++析构函数是否始终或仅在有时调用数据成员析构函数
- 根据C++标准,显式调用构造函数和析构函数是否安全
- std:map 析构函数是否调用键析构函数以及值析构函数?
- QNetworkAccessManager 析构函数是否中止当前请求
- 基类析构函数是否阻止生成移动构造函数
- 琐碎的析构函数是否会导致混叠
- 全局变量构造函数/析构函数是否需要线程保护
- 多态类的隐式析构函数是否可以成为虚拟的
- 默认的虚拟析构函数是否阻止编译器生成的移动操作
- 析构函数是否自动为成员变量解除分配堆内存
- 对象的析构函数是否释放用于创建对象的指针所指向的内存?