std:: uninitialized_copy_n
|
定义于头文件
<memory>
|
||
|
template
<
class
InputIt,
class
Size,
class
NoThrowForwardIt
>
NoThrowForwardIt uninitialized_copy_n
(
InputIt first, Size count,
|
(1) |
(C++11 起)
(C++26 起为 constexpr) |
|
template
<
class
ExecutionPolicy,
class
ForwardIt,
class
Size,
class
NoThrowForwardIt
>
|
(2) | (C++17 起) |
for
(
;
count
>
0
;
++
d_first,
(
void
)
++
first,
--
count
)
::
new
(
voidify
(
*
d_first
)
)
typename
std::
iterator_traits
<
NoThrowForwardIt
>
::
value_type
(
*
first
)
;
|
std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> 为 true 。 |
(C++20 前) |
|
std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> 为 true 。 |
(C++20 起) |
|
如果
d_first
|
(since 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)
|
将指定数量的对象复制到未初始化的内存区域
(算法函数对象) |