std::destroy
來自 cppreference.com
定義於標頭檔案 <memory> |
||
(1) | ||
template< class ForwardIt > void destroy( ForwardIt first, ForwardIt last ); |
(C++17 起) (C++20 前) |
|
template< class ForwardIt > constexpr void destroy( ForwardIt first, ForwardIt last ); |
(C++20 起) | |
template< class ExecutionPolicy, class ForwardIt > void destroy( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); |
(2) | (C++17 起) |
1) 銷燬範圍
[
first,
last)
中的物件,如同透過for (; first != last; ++first) std::destroy_at(std::addressof(*first));
2) 同 (1),但根據 policy 執行。此過載僅在滿足所有以下條件時參與過載決議:
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 為 true。 |
(C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 為 true。 |
(C++20 起) |
目錄 |
[編輯] 引數
first, last | - | 定義要銷燬的元素範圍的迭代器對 |
policy | - | 要使用的 執行策略 |
型別要求 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 | ||
-對 ForwardIt 的有效例項進行增量、賦值、比較或間接引用操作均不得丟擲異常。 |
[編輯] 返回值
(無)
[編輯] 複雜度
與 first 和 last 之間的距離呈線性關係。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 如果作為演算法一部分呼叫的函式執行時丟擲異常,且
ExecutionPolicy
是標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
template<class ForwardIt> constexpr // since C++20 void destroy(ForwardIt first, ForwardIt last) { for (; first != last; ++first) std::destroy_at(std::addressof(*first)); } |
[編輯] 示例
以下示例演示如何使用 destroy
銷燬連續的元素序列。
執行此程式碼
#include <iostream> #include <memory> #include <new> struct Tracer { int value; ~Tracer() { std::cout << value << " destructed\n"; } }; int main() { alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8]; for (int i = 0; i < 8; ++i) new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer)); std::destroy(ptr, ptr + 8); }
輸出
0 destructed 1 destructed 2 destructed 3 destructed 4 destructed 5 destructed 6 destructed 7 destructed
[編輯] 參閱
(C++17) |
銷燬範圍內的多個物件 (函式模板) |
(C++17) |
銷燬給定地址處的物件 (函式模板) |
(C++20) |
銷燬物件範圍 (演算法函式物件) |