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
是物件型別,則對於型別 U
,即 std::remove_all_extents<T>::type,如果表示式 std::declval<U&>().~U() 在未求值語境中是合法的,則 value 等於 true。否則,value 等於 false。3) 同 (1),但解構函式是 noexcept。
如果 T
不是完整型別,(可能 cv 限定的) void,或未知邊界陣列,則行為未定義。
如果上述模板的例項化直接或間接依賴於不完整型別,並且該例項化在該型別假設完成時可能產生不同的結果,則行為未定義。
如果程式為此頁上描述的任何模板新增特化,則行為未定義。
目錄 |
[編輯] 輔助變數模板
template< class T > constexpr bool is_destructible_v = is_destructible<T>::value; |
(C++17 起) | |
template< class T > constexpr bool is_trivially_destructible_v = is_trivially_destructible<T>::value; |
(C++17 起) | |
template< class T > constexpr bool is_nothrow_destructible_v = is_nothrow_destructible<T>::value; |
(C++17 起) | |
繼承自 std::integral_constant
成員常量
value [靜態] |
true 如果 T 是可析構的,否則為 false(public static 成員常量) |
成員函式
operator bool |
將物件轉換為 bool,返回 value (公開成員函式) |
operator() (C++14) |
返回 value (公開成員函式) |
成員型別
型別 | 定義 |
value_type
|
bool |
型別
|
std::integral_constant<bool, value> |
[編輯] 注意
因為如果解構函式在棧展開期間丟擲異常(這通常無法預測),C++ 程式就會終止,所以所有實際的解構函式都是不丟擲異常的,即使它們沒有宣告 `noexcept`。C++ 標準庫中所有的解構函式都是不丟擲異常的。
可平凡析構物件所佔用的儲存可以在不呼叫解構函式的情況下重用。
[編輯] 可能的實現
is_destructible (1) |
---|
// C++20 required template<typename t> struct is_destructible : std::integral_constant<bool, requires(t object) { object.~t(); }> {}; |
is_trivially_destructible (2) |
// Not real C++. Shall P2996 be approved, the following implementation will be available: template<typename t> struct is_trivially_destructible : std::integral_constant<bool, std::meta::type_is_trivially_destructible(^t)> {}; |
is_nothrow_destructible (3) |
// C++20 required template<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) |
指定該型別的物件可以被銷燬 (概念) |
解構函式 | 釋放已宣告的資源 |