std::uninitialized_copy() 算法
- 自 C++17 起
- C++17 之前
// (1)
template< class InputIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( InputIt first, InputIt last, NoThrowForwardIt d_first );
// (2)
template< class ExecutionPolicy, class ForwardIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
NoThrowForwardIt d_first );
// (1)
template< class InputIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( InputIt first, InputIt last, NoThrowForwardIt d_first );
-
(1) 将范围 [
first
;last
) 中的元素复制到从d_first
开始的未初始化内存区域,如同通过for (; first != last; ++d_first, (void) ++first)
::new (/* VOIDIFY */(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);其中
/* VOIDIFY */
是- 自 C++20 起
- 自 C++11 起
- 直到 C++11
voidify(e)
static_cast<void*>(std::addressof(e))
static_cast<void*>(&e)
注意如果在初始化期间抛出异常,则已构造的对象将以未指定顺序销毁。
未定义行为如果 d_first + [0
,std::distance(first, last)
) 与 [first
;last
) 重叠,则行为未定义。. (自 C++20 起) -
(2) 与 (1) 相同,但根据
policy
执行。
这些重载只有在 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(C++20 前) std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(C++20 起) 为 true
时才参与重载决议。
参数
first last | 要复制的元素范围。 |
d_first | 目标范围的开头。 |
policy | 要使用的执行策略。详见执行策略。 |
类型要求
InputIt | LegacyInputIterator |
ForwardIt NoThrowForwardIt | LegacyForwardIterator |
对 NoThrowForwardIt
的有效实例进行增量、赋值、比较或间接引用时,不得抛出异常。对 NoThrowForwardIt
值应用 &*
必须生成指向其值类型的指针。 (C++11 前)
返回值
指向复制的最后一个元素之后元素的迭代器。
复杂度
与 first
和 last
之间的距离成线性关系。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于其他任何ExecutionPolicy
,行为是实现定义的。. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
uninitialized_copy (1)
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_