std::uninitialized_value_construct
cppreference.com
<tbody>
</tbody>
template< class ForwardIt > void uninitialized_value_construct( ForwardIt first, ForwardIt last ); |
(1) | ( C++17) |
template< class ExecutionPolicy, class ForwardIt > void uninitialized_value_construct( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); |
(2) | ( C++17) |
1)
typename iterator_traits<ForwardIt>::value_type , [first, last), ,
for (; first != last; ++first)::new (static_cast<void*>(std::addressof(*first)))typename std::iterator_traits<ForwardIt>::value_type();
, .
2) , (1),
policy. , |
|
( C++20) |
|
|
( C++20) |
| first, last | ||
| policy | . . | |
-ForwardIt LegacyForwardIterator.
| ||
- , , ForwardIt .
| ||
()
first last.
ExecutionPolicy :
- , ,
ExecutionPolicy, std::terminate.ExecutionPolicy. - , std::bad_alloc.
template<class ForwardIt>
void uninitialized_value_construct(ForwardIt first, ForwardIt last)
{
using Value = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try
{
for (; current != last; ++current)
::new (const_cast<void*>(static_cast<const volatile void*>(
std::addressof(*current)))) Value();
}
catch (...)
{
std::destroy(first, current);
throw;
}
}
|
#include <iostream>
#include <memory>
#include <string>
int main()
{
struct S { std::string m{" "}; };
constexpr int n{3};
alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
try
{
auto first{reinterpret_cast<S*>(mem)};
auto last{first + n};
std::uninitialized_value_construct(first, last);
for (auto it{first}; it != last; ++it)
std::cout << it->m << '\n';
std::destroy(first, last);
}
catch (...)
{
std::cout << "!\n";
}
// , " " uninitialized_value_construct
// .
int v[]{1, 2, 3, 4};
for (const int i : v)
std::cout << i << ' ';
std::cout << '\n';
std::uninitialized_value_construct(std::begin(v), std::end(v));
for (const int i : v)
std::cout << i << ' ';
std::cout << '\n';
}
:
1 2 3 4
0 0 0 0
C++:
| LWG 3870 | C++20 | const
|
| , ( ) | |
| , ( ) | |
| , () |