std::destroy_n
來自 cppreference.com
定義於標頭檔案 <memory> |
||
(1) | ||
template< class ForwardIt, class Size > ForwardIt destroy_n( ForwardIt first, Size n ); |
(C++17 起) (C++20 前) |
|
template< class ForwardIt, class Size > constexpr ForwardIt destroy_n( ForwardIt first, Size n ); |
(C++20 起) | |
template< class ExecutionPolicy, class ForwardIt, class Size > ForwardIt destroy_n( ExecutionPolicy&& policy, ForwardIt first, Size n ); |
(2) | (C++17 起) |
1) 銷燬始於 first 的範圍中的 n 個物件,如同透過
for (; n > 0; (void) ++first, --n) 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 | - | 要銷燬的元素範圍的起始 |
n | - | 要銷燬的元素數量 |
policy | - | 要使用的 執行策略 |
型別要求 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 | ||
-對 ForwardIt 的有效例項進行自增、賦值、比較或間接引用均不得丟擲異常。 |
[編輯] 返回值
已被銷燬的物件範圍的末尾(即 std::next(first, n))。
[編輯] 複雜度
與 n 成線性關係。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 若作為演算法一部分呼叫的函式執行丟擲異常且
ExecutionPolicy
為標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
template<class ForwardIt, class Size> constexpr // since C++20 ForwardIt destroy_n(ForwardIt first, Size n) { for (; n > 0; (void) ++first, --n) std::destroy_at(std::addressof(*first)); return first; } |
[編輯] 示例
以下示例展示瞭如何使用 destroy_n
銷燬一個連續的元素序列。
執行此程式碼
#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_n(ptr, 8); }
輸出
0 destructed 1 destructed 2 destructed 3 destructed 4 destructed 5 destructed 6 destructed 7 destructed
[編輯] 參閱
(C++17) |
銷燬物件範圍 (函式模板) |
(C++17) |
銷燬給定地址處的物件 (函式模板) |
(C++20) |
銷燬範圍內的多個物件 (演算法函式物件) |