【问题标题】:Why is `std::uninitialized_copy/move etc.` not constexpr?为什么`std::uninitialized_copy/move etc.`不是constexpr?
【发布时间】:2021-05-07 20:04:17
【问题描述】:

我想知道为什么未初始化的存储功能像 https://en.cppreference.com/w/cpp/memory/uninitialized_copyhttps://en.cppreference.com/w/cpp/memory/uninitialized_move 在 C++20 中不是 constexpr 吗?

放弃提供的“可能的实现”,难道只需要转换

template<class InputIt, class ForwardIt>
ForwardIt uninitialized_copy(InputIt first, InputIt last, ForwardIt d_first)
{
    typedef typename std::iterator_traits<ForwardIt>::value_type Value;
    ForwardIt current = d_first;
    try {
        for (; first != last; ++first, (void) ++current) {
            ::new (static_cast<void*>(std::addressof(*current))) Value(*first);
        }
        return current;
    } catch (...) {
        for (; d_first != current; ++d_first) {
            d_first->~Value();
        }
        throw;
    }
}

template<class InputIt, class ForwardIt>
constexpr ForwardIt uninitialized_copy(InputIt first, InputIt last, ForwardIt d_first)
{
    typedef typename std::iterator_traits<ForwardIt>::value_type Value;
    ForwardIt current = d_first;
    try {
        for (; first != last; ++first, (void) ++current) {
            std::construct_at(current, *first); // <---- THIS
        }
        return current;
    } catch (...) {
        for (; d_first != current; ++d_first) {
            d_first->~Value();
        }
        throw;
    }
}

对于uninitialized_copy 的情况?还是我错过了什么?

【问题讨论】:

    标签: c++ constexpr c++20


    【解决方案1】:

    P2283

    uninitialized_copy 是正确的,您只需将新展示位置更改为 std::construct_at

    但是对于uninitialized_default_construct,您不能只使用std::construct_at,因为它会进行值初始化并且算法需要进行默认初始化。该论文建议使用新的std::default_construct_at 作为该问题的解决方案。

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 2020-08-06
      • 2012-07-28
      • 1970-01-01
      相关资源
      最近更新 更多