C++11标准模板(STL)- 动态内存管理 - 未初始化存储 - 将范围内的对象复制到未初始化的内存区域 - (std::uninitialized_copy)

动态内存管理

未初始化存储

提供数个工具以创建并访问未初始化存储

将范围内的对象复制到未初始化的内存区域

std::uninitialized_copy

template< class InputIt, class ForwardIt >
ForwardIt uninitialized_copy( InputIt first, InputIt last, ForwardIt d_first );

(1)

template< class ExecutionPolicy, class InputIt, class ForwardIt >
ForwardIt uninitialized_copy( ExecutionPolicy&& policy, InputIt first, InputIt last, ForwardIt d_first );

(2)(C++17 起)

1) 复制来自范围 [first, last) 的元素到始于 d_first 的未初始化内存,如同用

for (; first != last; ++d_first, (void) ++first)
   ::new (static_cast<void*>(std::addressof(*d_first)))
      typename std::iterator_traits<ForwardIt>::value_type(*first);

若初始化中抛异常,则以未指定顺序销毁已构造的对象。

2) 同 (1) ,但按照 policy 执行。此重载仅若 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 为 true 才参与重载决议。

参数

first, last-要复制的元素范围
d_first-目标范围的起始
policy-所用的执行策略。细节见执行策略。
类型要求
- InputIt 必须满足遗留输入迭代器 (LegacyInputIterator) 的要求。
- ForwardIt 必须满足遗留向前迭代器 (LegacyForwardIterator) 的要求。
- 通过ForwardIt 合法实例的自增、赋值、比较或间接均不可抛异常。

返回值

指向最后复制的元素后一元素的迭代器。

复杂度

firstlast 间的距离成线性

异常

拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:

  • 若作为算法一部分调用的函数的执行抛出异常,且 ExecutionPolicy 为标准策略之一,则调用 std::terminate 。对于任何其他 ExecutionPolicy ,行为是实现定义的。
  • 若算法无法分配内存,则抛出 std::bad_alloc 。

可能的实现

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;
    }
}

调用示例

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <functional>
#include <time.h>
#include <random>
#include <vector>
#include <cassert>

struct Cell
{
    int x;
    int y;

    Cell() = default;
    Cell(int a, int b): x(a), y(b) {}

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator +(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator *(const Cell &cell)
    {
        x *= cell.x;
        y *= cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }


    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator >(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y > cell.y;
        }
        else
        {
            return x > cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }

    friend Cell operator+(const Cell &lcell, const Cell &rcell)
    {
        Cell cell = lcell;
        cell.x += rcell.x;
        cell.y += rcell.y;
        return cell;
    }

    friend Cell operator-(const Cell &lcell, const Cell &rcell)
    {
        Cell cell = lcell;
        cell.x -= rcell.x;
        cell.y -= rcell.y;
        return cell;
    }

    friend Cell operator*(const Cell &lcell, const Cell &rcell)
    {
        Cell cell = lcell;
        cell.x *= rcell.x;
        cell.y *= rcell.y;
        return cell;
    }

    friend Cell operator/(const Cell &lcell, const Cell &rcell)
    {
        Cell cell = lcell;
        cell.x /= rcell.x;
        cell.y /= rcell.y;
        return cell;
    }

    friend Cell operator%(const Cell &lcell, const Cell &rcell)
    {
        Cell cell = lcell;
        cell.x %= rcell.x;
        cell.y %= rcell.y;
        return cell;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

namespace _std
{
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;
    }
}
}

int main()
{
    std::cout << std::boolalpha;

    std::mt19937 g{std::random_device{}()};
    srand((unsigned)time(NULL));

    auto generate = []()
    {
        int n = std::rand() % 10 + 110;
        Cell cell{n, n};
        return cell;
    };

    //3) 构造拥有 count 个有值 value 的元素的容器。
    std::vector<Cell> vector1(8, generate());
    std::generate(vector1.begin(), vector1.end(), generate);
    std::sort(vector1.begin(), vector1.end());
    std::cout << "vector1:  ";
    std::copy(vector1.begin(), vector1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    std::vector<Cell> vector2(vector1.size(), Cell{101, 101});
    std::generate(vector2.begin(), vector2.end(), generate);
    std::sort(vector2.begin(), vector2.end());
    std::cout << "vector2:  ";
    std::copy(vector2.begin(), vector2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    std::vector<Cell> vector3;
    // 为vector3预留空间
    vector3.resize(vector1.size());
    std::uninitialized_copy(vector1.begin(), vector1.end(), vector3.begin());
    std::cout << "vector3:  ";
    std::copy(vector3.begin(), vector3.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "vector1:  ";
    std::copy(vector1.begin(), vector1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}

输出

vector1:  {110,110} {111,111} {112,112} {114,114} {114,114} {115,115} {116,116} {119,119}
vector2:  {111,111} {113,113} {113,113} {116,116} {116,116} {117,117} {117,117} {118,118}
vector3:  {110,110} {111,111} {112,112} {114,114} {114,114} {115,115} {116,116} {119,119}
vector1:  {110,110} {111,111} {112,112} {114,114} {114,114} {115,115} {116,116} {119,119}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值