std::uninitialized_copy
来自cppreference.com
| 在标头 <memory> 定义
|
||
| (1) | (C++26 起为 constexpr) | |
| |
(2) | (C++17 起) |
1) 如同用以下方式以源范围
[first, last) 中的元素构造从 d_first 开始的目标范围中的元素:
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++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 866 | C++98 | 给定 T 为 NoThrowForwardIt 的值类型,如果存在 T::operator new,那么程序可能会非良构
|
改用全局的布置 new |
| LWG 2133 | C++98 | 效果描述用到了迭代表达式是 ++d_first, ++first 的for 循环,该表达式会进行 operator, 的实参依赖查找
|
丢弃其中一个操作数的值 以禁用该实参依赖查找 |
| LWG 2433 | C++11 | 此算法可能被重载的 operator& 劫持
|
使用 std::addressof |
参阅
(C++11) |
复制若干对象到未初始化内存 (函数模板 & 算法函数对象) |
(C++20) |
|
(C++20) |
复制范围中对象到未初始化内存 (算法函数对象) |