std::is_destructible, std::is_trivially_destructible, std::is_nothrow_destructible
出自cppreference.com
| 在標頭 <type_traits> 定義
|
||
| (1) | (C++11 起) | |
| (2) | (C++11 起) | |
| (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 或未知邊界數組,那麼行為未定義。
如果上述模板的實例化直接或間接地依賴於不完整類型,並且假設在該類型完整的情況下實例化就會產生不同的結果,那麼行為未定義。
如果程序添加了此頁面上描述的任何模板的特化,那麼行為未定義。
輔助變量模板
| |
(C++17 起) | |
| |
(C++17 起) | |
| |
(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++20
template<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++20
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) |
指定能銷毀該類型的對象 (概念) |
| 析構函數 | 釋放所獲取的資源 |