std::uninitialized_copy_n
来自cppreference.com
<tbody>
</tbody>
| 在标头 <memory> 定义
|
||
template< class InputIt, class Size, class NoThrowForwardIt > NoThrowForwardIt uninitialized_copy_n( InputIt first, Size count, NoThrowForwardIt d_first ); |
(1) | (C++11 起) (C++26 起为 constexpr) |
template< class ExecutionPolicy, class ForwardIt, class Size, class NoThrowForwardIt > NoThrowForwardIt uninitialized_copy_n( ExecutionPolicy&& policy, ForwardIt first, Size count, NoThrowForwardIt d_first ); |
(2) | (C++17 起) |
1) 如同用以下方式从始于
first 的范围复制 count 个元素到始于 d_first 的未初始化内存区域:
for (; count > 0; ++d_first, (void) ++first, --count)
::new (voidify(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);
如果初始化中抛出了异常,那么以未指定的顺序销毁已构造的对象。
2) 同 (1),但按照
policy 执行。 此重载只有在满足以下所有条件时才会参与重载决议:
|
|
(C++20 前) |
|
|
(C++20 起) |
|
如果 |
(C++20 起) |
参数
| first | - | 要复制的元素范围起始 |
| count | - | 要复制的元素个数 |
| d_first | - | 目标范围起始 |
| policy | - | 所用的执行策略 |
| 类型要求 | ||
-InputIt 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
-ForwardIt 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-NoThrowForwardIt 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-通过 NoThrowForwardIt 合法实例的自增、赋值、比较或间接均不可抛异常。
| ||
返回值
指向最后复制的元素后一元素的迭代器。
复杂度
与 count 成线性。
异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 的特化内存算法, (1)
|
可能的实现
template<class InputIt, class Size, class NoThrowForwardIt>
constexpr NoThrowForwardIt uninitialized_copy_n(InputIt first, Size count,
NoThrowForwardIt d_first)
{
using T = typename std::iterator_traits<NoThrowForwardIt>::value_type;
NoThrowForwardIt current = d_first;
try
{
for (; count > 0; ++first, (void) ++current, --count)
::new (static_cast<void*>(std::addressof(*current))) T(*first);
}
catch (...)
{
for (; d_first != current; ++d_first)
d_first->~T();
throw;
}
return current;
}
|
示例
运行此代码
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
int main()
{
std::vector<std::string> v = {"This", "is", "an", "example"};
std::string* p;
std::size_t sz;
std::tie(p, sz) = std::get_temporary_buffer<std::string>(v.size());
sz = std::min(sz, v.size());
std::uninitialized_copy_n(v.begin(), sz, p);
for (std::string* i = p; i != p + sz; ++i)
{
std::cout << *i << ' ';
i->~basic_string<char>();
}
std::cout << '\n';
std::return_temporary_buffer(p);
}
可能的输出:
This is an example
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2133 | C++98 | 效果描述用到了迭代表达式是 ++d_first, ++first, --count的 for 循环,该表达式会进行 operator, 的实参依赖查找
|
丢弃其中一个操作数的值 以禁用该实参依赖查找 |
| LWG 2433 | C++11 | 此算法可能被重载的 operator& 劫持
|
使用 std::addressof |
| LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象
|
保持不允许 |
参阅
| 复制范围中对象到未初始化内存 (函数模板) | |
(C++20) |
复制若干对象到未初始化内存 (算法函数对象) |