std::ranges::destroy
来自cppreference.com
定义于头文件 <memory>
|
||
调用签名 |
||
template< no-throw-input-iterator I, no-throw-sentinel-for<I> S > requires std::destructible<std::iter_value_t<I>> |
(1) | (C++20 起) |
template< no-throw-input-range R > requires std::destructible<ranges::range_value_t<R>> |
(2) | (C++20 起) |
1) 销毁范围
[first, last)
中的对象,如同用
for (; first != last; ++first) std::ranges::destroy_at(std::addressof(*first)); return first;
2) 同 (1) ,但以
r
为源范围,如同以 ranges::begin(r) 为 first
并以 ranges::end(r) 为 last
。此页面上描述的仿函数实体是 niebloid ,即:
实际上,它们能以函数对象,或以某些特殊编译器扩展实现。
参数
first, last | - | 代表要销毁的范围的迭代器-哨位对 |
r | - | 要销毁的范围 |
返回值
比较等于 last
的迭代器。
复杂度
与 first
和 last
间的距离成线性。
可能的实现
struct destroy_fn { template<no-throw-input-iterator I, no-throw-sentinel-for<I> S> requires std::destructible<std::iter_value_t<I>> constexpr I operator()(I first, S last) const noexcept { for (; first != last; ++first) std::ranges::destroy_at(std::addressof(*first)); return first; } template<no-throw-input-range R> requires std::destructible<std::ranges::range_value_t<R>> constexpr std::ranges::borrowed_iterator_t<R> operator()(R&& r) const noexcept { return operator()(std::ranges::begin(r), std::ranges::end(r)); } }; inline constexpr destroy_fn destroy{}; |
示例
下列示例演示如何用 ranges::destroy
销毁元素的相接序列。
运行此代码
#include <memory> #include <new> #include <iostream> 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}; // 手工构造对象 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++20) |
销毁范围中一定量的元素 (niebloid) |
(C++20) |
销毁位于给定地址的元素 (niebloid) |
(C++17) |
销毁一个范围中的对象 (函数模板) |