std::uninitialized_copy
|
在标头
<memory>
定义
|
||
template< class InputIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( InputIt
first, InputIt last, |
(1) | |
template< class ExecutionPolicy,
class ForwardIt, class
NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy(
ExecutionPolicy&& policy, |
(2) | (C++17 起) |
[
first,
last)
中的元素复制到从
d_first 开始的未初始化内存:
for (; first != last; ++d_first, (void) ++first)::new (/* VOIDIFY */(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);
|
(C++11 前) |
|
(C++11 起) (C++20 前) |
|
(C++20 起) |
如果 d_first |
(C++20 起) |
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> |
(C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> |
(C++20 起) |
参数
first, last | - | 要复制的元素范围 |
d_first | - | 目标范围的起始 |
policy | - | 所用的执行策略。细节见执行策略。 |
类型要求 | ||
-InputIt 必须符合老式输入迭代器 (LegacyInputIterator)
的要求。
|
||
-ForwardIt 必须符合老式向前迭代器 (LegacyForwardIterator)
的要求。
|
||
-NoThrowForwardIt 必须符合老式向前迭代器 (LegacyForwardIterator)
的要求。
|
||
-通过 NoThrowForwardIt
合法实例的自增、赋值、比较或间接均不可抛异常。将 &* 应用到 NoThrowForwardIt
值的情况下必须产生指向它的值类型的指针。 (C++11
前)
|
返回值
指向最后复制的元素后一元素的迭代器。
复杂度
与 first 和 last 间的距离成线性。
异常
拥有名为 ExecutionPolicy
的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy
是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy
,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
可能的实现
template<class InputIt, class NoThrowForwardIt> NoThrowForwardIt uninitialized_copy(InputIt first, InputIt last, NoThrowForwardIt d_first) { using T = typename std::iterator_traits<NoThrowForwardIt>::value_type; NoThrowForwardIt current = d_first; try { for (; first != last; ++first, (void) ++current) ::new (static_cast<void*>(std::addressof(*current))) T(*first); return current; } catch (...) { for (; d_first != current; ++d_first) d_first->~T(); throw; } } |
示例
#include <cstdlib> #include <iostream> #include <memory> #include <string> int main() { const char *v[] = {"This", "is", "an", "example"}; auto sz = std::size(v); if (void *pbuf = std::aligned_alloc(alignof(std::string), sizeof(std::string) * sz)) { try { auto first = static_cast<std::string*>(pbuf); auto last = std::uninitialized_copy(std::begin(v), std::end(v), first); for (auto it = first; it != last; ++it) std::cout << *it << '_'; std::cout << '\n'; std::destroy(first, last); } catch (...) {} std::free(pbuf); } }
输出:
This_is_an_example_
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 866 | C++98 | 给定 T 为 NoThrowForwardIt 的值类型,如果存在 T::operator new,那么程序可能会非良构 |
改用全局的布置 new |
LWG 2433 | C++11 | 此算法可能被重载的 operator& 劫持 | 使用 std::addressof |
LWG 3870 | C++20 | 此算法可以在 const 存储上创建对象 | 保持不允许 |
参阅
(C++11)
|
将指定数量的对象复制到未初始化的内存区域 (函数模板) |
(C++20)
|
复制元素范围到未初始化的内存区域 (niebloid) |