std::ranges:: uninitialized_fill
|
定义于头文件
<memory>
|
||
|
调用签名
|
||
|
template
<
no-throw-forward-iterator
I, no
-
throw
-
sentinel
-
for
<
I
>
S,
class
T
>
|
(1) |
(C++20 起)
(C++26 起为 constexpr) |
|
template
<
no-throw-forward-range
R,
class
T
>
requires
std::
constructible_from
<
ranges::
range_value_t
<
R
>
,
|
(2) |
(C++20 起)
(C++26 起为 constexpr) |
[
first
,
last
)
,其行为类似于:
for
(
;
first
!
=
last
;
++
first
)
::
new
(
voidify
(
*
first
)
)
std::
remove_reference_t
<
std::
iter_reference_t
<
I
>>
(
value
)
;
return
first
;
本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:
目录 |
参数
| first, last | - | 定义待初始化元素 范围 的迭代器-哨位对 |
| r | - |
待初始化元素的
range
|
| value | - | 用于构造元素的值 |
返回值
如上所述。
复杂度
与未初始化内存区域的大小呈线性关系。
异常
在目标范围元素构造过程中抛出的任何异常。
注释
若输出范围的
值类型
为
平凡类型
,实现可通过使用
ranges::fill
等方式提升
ranges::uninitialized_fill
的执行效率。
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms
|
202411L
|
(C++26) | constexpr for 专用内存算法 , ( 1,2 ) |
可能的实现
struct uninitialized_fill_fn { template<no-throw-forward-iterator I, no-throw-sentinel-for<I> S, class T> requires std::constructible_from<std::iter_value_t<I>, const T&> constexpr I operator()(I first, S last, const T& value) const { I rollback{first}; try { for (; !(first == last); ++first) ranges::construct_at(std::addressof(*first), value); return first; } catch (...) { // 回滚:销毁已构造的元素 for (; rollback != first; ++rollback) ranges::destroy_at(std::addressof(*rollback)); throw; } } template<no-throw-forward-range R, class T> requires std::constructible_from<ranges::range_value_t<R>, const T&> constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, const T& value) const { return (*this)(ranges::begin(r), ranges::end(r), value); } }; inline constexpr uninitialized_fill_fn uninitialized_fill{}; |
示例
#include <iostream> #include <memory> #include <string> int main() { constexpr int n{4}; alignas(alignof(std::string)) char out[n * sizeof(std::string)]; try { auto first{reinterpret_cast<std::string*>(out)}; auto last{first + n}; std::ranges::uninitialized_fill(first, last, "▄▀▄▀▄▀▄▀"); int count{1}; for (auto it{first}; it != last; ++it) std::cout << count++ << ' ' << *it << '\n'; std::ranges::destroy(first, last); } catch(...) { std::cout << "Exception!\n"; } }
输出:
1 ▄▀▄▀▄▀▄▀ 2 ▄▀▄▀▄▀▄▀ 3 ▄▀▄▀▄▀▄▀ 4 ▄▀▄▀▄▀▄▀
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| DR | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3870 | C++20 | 该算法可能在 const 存储上创建对象 | 保持禁止状态 |
参见
|
(C++20)
|
将对象复制到由起始位置和数量定义的未初始化内存区域
(算法函数对象) |
|
将对象复制到由范围定义的未初始化内存区域
(函数模板) |