std::uninitialized_copy_n
来自 zh.cppreference.net
| 定义于头文件 <memory>
|
||
template< class InputIt, class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( InputIt first, Size count,
NoThrowForwardIt d_first );
|
(1) | (自 C++11 起) (自 C++26 起 constexpr) |
template< class ExecutionPolicy, class ForwardIt,
class Size, class NoThrowForwardIt >
NoThrowForwardIt uninitialized_copy_n( ExecutionPolicy&& policy,
ForwardIt first, Size count,
NoThrowForwardIt d_first );
|
(2) | (自 C++17 起) |
1) 在目标范围(起始于
d_first)中构造元素,从源范围(起始于 count)中的前 first 个元素复制,效果如同
for (; count > 0; ++d_first, (void) ++first, --count)
::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 | - | 要复制的元素范围的起始 |
| count | - | 要复制的元素数量 |
| d_first | - | 目标范围的起始 |
| policy | - | 要使用的 执行策略 |
| 类型要求 | ||
-InputIt 必须满足 LegacyInputIterator 的要求。
| ||
-ForwardIt 必须满足 LegacyForwardIterator 的要求。
| ||
-NoThrowForwardIt 必须满足 LegacyForwardIterator 的要求。
| ||
-对于有效的 NoThrowForwardIt 实例,递增、赋值、比较或间接引用操作不得抛出异常。
| ||
返回值
如上所述。
异常
2) 在执行过程中:
- 如果并行化所需的临时内存资源不可用,则抛出 std::bad_alloc。
- 如果在通过算法参数访问对象时抛出了未捕获的异常,则行为由执行策略决定(对于 标准策略,std::terminate 被调用)。
备注
| 功能测试宏 | 值 | 标准 | 特性 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 用于 特化 <memory>算法, (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++ 标准。
| DR | 应用于 | 已发布的行为 | 正确行为 |
|---|---|---|---|
| LWG 2133 | C++98 | 效果描述使用了一个for循环,迭代表达式 ++d_first, ++first, --count,这导致了对 operator,
|
丢弃了值 的一个操作数,以 禁用那些 ADL |
| LWG 2433 | C++11 | 这个算法可能被重载的operator&
|
使用std::addressof |
参见
|
将对象范围复制到未初始化的内存区域
(函数模板) |
|
|
(C++20)
|
将指定数量的对象复制到未初始化的内存区域
(算法函数对象) |