◐ Shell
clean mode source ↗

std::uninitialized_default_construct_n - cppreference.com

来自cppreference.com

在标头 <memory> 定义

template< class NoThrowForwardIt, class Size >
NoThrowForwardIt uninitialized_default_construct_n
    ( NoThrowForwardIt first, Size count );
(1) (C++17 起)
(C++26 起为 constexpr)
template< class ExecutionPolicy, class NoThrowForwardIt, class Size >
NoThrowForwardIt uninitialized_default_construct_n
    ( ExecutionPolicy&& policy, NoThrowForwardIt first, Size count );
(2) (C++17 起)

1) 如同用以下方式通过默认初始化构造目标范围 first + [0count) 中的元素:

for (; count > 0; (void)++first, --count)
    ::new (voidify(*first))
        typename std::iterator_traits<NoThrowForwardIt>::value_type;
return first;

如果初始化中抛出了异常,那么以未指定的顺序销毁已构造的对象。

2)(1),但按照 policy 执行。

此重载只有在以下表达式的值是 true 时才会参与重载决议:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20 前)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20 起)

参数

first - 要初始化的元素范围的起始
count - 要初始化的元素个数
policy - 所用的执行策略
类型要求
-NoThrowForwardIt 必须满足老式向前迭代器 (LegacyForwardIterator)
-通过 NoThrowForwardIt 合法实例的自增、赋值、比较或间接均不抛出异常。

返回值

如上所述。

异常

2) 在执行过程中:

  • 如果并行化所需的临时内存资源不可用,那么就会抛出 std::bad_alloc
  • 如果在通过算法实参访问对象时抛出了未捕获的异常,那么行为由执行策略决定(标准策略会调用 std::terminate)。

注解

功能特性测试 标准 功能特性
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr<memory> 专门算法, (1)

可能的实现

template<class NoThrowForwardIt, class Size>
constexpr ForwardIt uninitialized_default_construct_n(NoThrowForwardIt first, Size count)
{
    using T = typename std::iterator_traits<NoThrowForwardIt>::value_type;
    NoThrowForwardIt current = first;
    
    try
    {
        for (; countn > 0; (void) ++current, --count)
            ::new (static_cast<void*>(std::addressof(*current))) T;
        return current;
    }
    catch (...)
    {
        std::destroy(first, current);
        throw;
    }
}

示例

#include <cstring>
#include <iostream>
#include <memory>
#include <string>

struct S
{
    std::string m{"默认值"};
};

int main()
{
    constexpr int n{3};
    alignas(alignof(S)) unsigned char mem[n * sizeof(S)];
    
    try
    {
        auto first{reinterpret_cast<S*>(mem)};
        auto last = std::uninitialized_default_construct_n(first, n);
        
        for (auto it{first}; it != last; ++it)
            std::cout << it->m << '\n';
        
        std::destroy(first, last);
    }
    catch(...)
    {
        std::cout << "异常!\n";
    }
    
    // 对于标量类型,uninitialized_default_construct_n
    // 通常不会以零填充未初始化的内存区域。
    int v[]{1, 2, 3, 4};
    const int original[]{1, 2, 3, 4};
    std::uninitialized_default_construct_n(std::begin(v), std::size(v));
    
    // 可能是未定义行为,等待 CWG 1997 得到解决:
    // for (const int i : v)
    //     std::cout << i << ' ';
    
    // 结果未指定:
    std::cout << (std::memcmp(v, original, sizeof(v)) == 0 ? "未修改\n" : "已修改\n");
}

可能的输出:

参阅