std::uninitialized_copy
来自 zh.cppreference.net
| 定义于头文件 <memory>
|
||
template< class InputIt, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( InputIt first, InputIt last,
NoThrowForwardIt d_first );
|
(1) | (自 C++26 起 constexpr) |
template< class ExecutionPolicy, class ForwardIt,
class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last,
NoThrowForwardIt d_first );
|
(2) | (自 C++17 起) |
1) 在目标范围(始于
d_first)中从源范围 [first, last) 按以下方式构造元素:
for (; first != last; ++d_first, (void) ++first)
::new (voidify(*d_first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(*first);
return d_first;
若初始化期间抛出异常,则以未指定的顺序销毁已构造的对象。
2) 与 (1) 相同,但按
policy 执行。 仅当下表达式的值为
true 时,此重载参与重载决议:
|
|
(直到 C++20) |
|
|
(自 C++20 起) |
|
若 |
(自 C++20 起) |
参数
| first, last | - | 定义待复制元素 范围 的迭代器对 |
| d_first | - | 目标范围的起始位置 |
| policy | - | 使用的 执行策略 |
| 类型要求 | ||
-
InputIt
必须满足
LegacyInputIterator
的要求。
|
||
-
ForwardIt
必须满足
LegacyForwardIterator
的要求。
|
||
-
NoThrowForwardIt
必须满足
LegacyForwardIterator
的要求。
|
||
-
NoThrowForwardIt
有效实例进行递增、赋值、比较或解引用操作均不得抛出异常。
对
NoThrowForwardIt
值应用
&
*
必须得到指向其值类型的指针。
(C++11 前)
|
||
返回值
如上所述。
异常
2) 在执行过程中:
- 如果并行化所需的临时内存资源不可用,则std::bad_alloc被抛出。
- 如果通过算法参数访问对象时抛出未捕获的异常,则行为由执行策略决定(对于标准策略,会调用std::terminate)。
注释
| 特性测试宏 | 值 | 标准 | 特性 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr用于特化<memory>算法,(1)
|
可能的实现
template<class InputIt, class NoThrowForwardIt> constexpr 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++ 标准。
| DR | 应用于 | 已发布行为 | 正确行为 |
|---|---|---|---|
| LWG 866 | C++98 | 如果将 T 作为 NoThrowForwardIt 的值类型,且存在 T::operator new,则程序可能为非良构
|
转而使用全局替换 new |
| LWG 2133 | C++98 | 效果描述使用了 for 循环,其迭代表达式为 ++d_first, ++first,这导致在参数依赖查找中 operator,
|
丢弃了 一个操作数的值 以禁用该 ADL |
| LWG 2433 | C++11 | 此算法可能被重载的 operator&
|
劫持,改用 std::addressof |
另见
(C++11) |
将多个对象复制到未初始化的内存区域 (函数模板 & 算法函数对象) |
(C++20) |
|
(C++20) |
将一定范围的对象复制到未初始化的内存区域 (算法函数对象) |