std::ranges::uninitialized_value_construct
来自cppreference.com
| 在标头 <memory> 定义
|
||
| 调用签名 |
||
| (1) | (C++20 起) (C++26 起为 constexpr) |
|
| (2) | (C++20 起) (C++26 起为 constexpr) |
|
1) 如同用以下方式在未初始化内存区域
[first, last) 上通过值初始化构造 std::iter_value_t<I> 类型对象:
for (; first != last; ++first)
::new (voidify(*first))
std::remove_reference_t<std::iter_reference_t<I>>();
return first;
如果初始化中抛出了异常,那么以未指定的顺序销毁已构造的对象。
2) 等价于
ranges::uninitialized_value_construct(ranges::begin(r), ranges::end(r))。此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:
参数
| first, last | - | 要值初始化的元素范围的迭代器-哨位对 |
| r | - | 要值初始化的元素 range
|
返回值
如上所述。
复杂度
与 first 和 last 间的距离成线性。
异常
构造目标范围中的元素时抛出的任何异常。
注解
如果范围的值类型是可复制赋值 (CopyAssignable) 的平凡类型 (TrivialType) ,那么实现可以提升 ranges::uninitialized_value_construct 的效率,例如用 ranges::fill。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 的特化内存算法, (1,2)
|
可能的实现
struct uninitialized_value_construct_fn
{
template<no-throw-forward-iterator I, no-throw-sentinel-for<I> S>
requires std::value_initializable<std::iter_value_t<I>>
constexpr I operator()(I first, S last) const
{
using ValueType = std::remove_reference_t<std::iter_reference_t<I>>;
if constexpr (std::is_trivially_default_constructible_v<ValueType>)
return ranges::fill(first, last, ValueType());
I rollback{first};
try
{
for (; !(first == last); ++first)
::new (static_cast<void*>(std::addressof(*first))) ValueType();
return first;
}
catch (...) // 回滚:销毁构造的元素
{
for (; rollback != first; ++rollback)
ranges::destroy_at(std::addressof(*rollback));
throw;
}
}
template<no-throw-forward-range R>
requires std::default_initializable<ranges::range_value_t<R>>
constexpr ranges::borrowed_iterator_t<R> operator()(R&& r) const
{
return (*this)(ranges::begin(r), ranges::end(r));
}
};
inline constexpr uninitialized_value_construct_fn uninitialized_value_construct{};
|
示例
运行此代码
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{"▄▀▄▀▄▀▄▀"}; };
constexpr int n{4};
alignas(alignof(S)) char out[n * sizeof(S)];
try
{
auto first{reinterpret_cast<S*>(out)};
auto last{first + n};
std::ranges::uninitialized_value_construct(first, last);
auto count{1};
for (auto it{first}; it != last; ++it)
std::cout << count++ << ' ' << it->m << '\n';
std::ranges::destroy(first, last);
}
catch (...)
{
std::cout << "异常!\n";
}
// 对于标量类型,uninitialized_value_construct
// 会以零填充给定的未初始化内存区域。
int v[]{0, 1, 2, 3};
std::cout << ' ';
for (const int i : v)
std::cout << ' ' << static_cast<char>(i + 'A');
std::cout << "\n ";
std::ranges::uninitialized_value_construct(std::begin(v), std::end(v));
for (const int i : v)
std::cout << ' ' << static_cast<char>(i + 'A');
std::cout << '\n';
}
输出:
1 ▄▀▄▀▄▀▄▀
2 ▄▀▄▀▄▀▄▀
3 ▄▀▄▀▄▀▄▀
4 ▄▀▄▀▄▀▄▀
A B C D
A A A A
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象
|
保持禁止 |
