std::is_destructible, std::is_trivially_destructible, std::is_nothrow_destructible
来自cppreference.com
在标头 <type_traits> 定义 | ||
template<class T > struct is_destructible; | (1) | (C++11 起) |
template<class T > struct is_trivially_destructible; | (2) | (C++11 起) |
template<class T > struct is_nothrow_destructible; | (3) | (C++11 起) |
1) 如果
T
是引用类型,则提供的成员常量 value 等于 true。 如果
T
是(可以有 cv 限定的)void、函数类型或未知边界的数组,则 value 等于 false。 如果
T
是对象类型,则对于作为 std::remove_all_extents<T>::type 的类型 U
,如果表达式 std::declval<U&>().~U() 在不求值语境中良构,则 value 等于 true。否则,value 等于 false。3) 同 (1),但析构函数为 noexcept。
如果 T
不是完整类型,(可有 cv 限定的)void 或未知边界数组,那么行为未定义。
如果上述模板的实例化直接或间接地依赖于不完整类型,并且假设在该类型完整的情况下实例化就会产生不同的结果,那么行为未定义。
如果程序添加了此页面上描述的任何模板的特化,那么行为未定义。
目录 |
[编辑]辅助变量模板
template<class T > constexprbool is_destructible_v = is_destructible<T>::value; | (C++17 起) | |
template<class T > constexprbool is_trivially_destructible_v = is_trivially_destructible<T>::value; | (C++17 起) | |
template<class T > constexprbool is_nothrow_destructible_v = is_nothrow_destructible<T>::value; | (C++17 起) | |
继承自 std::integral_constant
成员常量
value [静态] | 如果 T 可析构那么是 true,否则是 false(公开静态成员常量) |
成员函数
operator bool | 将对象转换到 bool,返回 value (公开成员函数) |
operator() (C++14) | 返回 value (公开成员函数) |
成员类型
类型 | 定义 |
value_type | bool |
type | std::integral_constant<bool, value> |
[编辑]注解
因为析构函数在栈回溯中抛出异常则 C++ 程序终止(通常是无法预期的),所以所有实用的析构函数均为不抛出,即使它们不声明为 noexcept。所有 C++ 标准库中析构函数都是不抛出的。
[编辑]可能的实现
is_destructible (1) |
---|
// 要求 C++20template<typename t>struct is_destructible :std::integral_constant<bool, requires(t object){ object.~t();}>{}; |
is_trivially_destructible (2) |
// 不是真正的 C++。应当采纳 P2996,才能使以下实现可用:template<typename t>struct is_trivially_destructible :std::integral_constant<bool, std::meta::type_is_trivially_destructible(^t)>{}; |
is_nothrow_destructible (3) |
// 要求 C++20template<typename t>struct is_nothrow_destructible :std::integral_constant<bool, requires(t object){{object.~t()}noexcept;}>{}; |
[编辑]示例
运行此代码
#include <iostream>#include <string>#include <type_traits> struct Foo {std::string str; ~Foo()noexcept{};}; struct Bar { ~Bar()=default;}; static_assert(std::is_destructible<std::string>::value==true); static_assert(std::is_trivially_destructible_v<Foo>==false); static_assert(std::is_nothrow_destructible<Foo>()==true); static_assert(std::is_trivially_destructible<Bar>{}==true); int main(){}
[编辑]缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2049 | C++11 | 规范无法完整,由于虚构的包装结构体 | 使之完整 |
[编辑]参阅
(C++11)(C++11)(C++11) | 检查类型是否带有针对特定实参的构造函数 (类模板) |
(C++11) | 检查类型是否有虚析构函数 (类模板) |
(C++20) | 指定能销毁该类型的对象 (概念) |
析构函数 | 释放所获取的资源 |