在C ++中为我自己的基于指针的数组分配内存的正确方法

时间:2018-10-26 13:48:58

标签: c++ data-structures new-operator dynamic-memory-allocation raw-pointer

我已经搜索了类似的问题,但是找不到满足我需求的东西。

我是一名计算机科学专业的学生,​​目前正在学习算法和数据结构。对于我的考试,我必须用C ++实现一组模板化数据结构。不允许使用STL,因为这是关于如何实现与STL类似的库的考试问题。

我的实现工作正常,但是我想问您有关动态内存分配的建议。

其中一些数据结构使用动态数组(实际上是原始指针)来存储元素,该元素在满时会自动增长,并在某个负载因子阈值(分别为其大小的两倍和一半)以下收缩时会自动增长。为了简单起见(也因为我不应该使用它们),我没有使用任何“现代的东西”,例如智能指针或移动构造函数/ operator =,基本上我依赖于C ++ 98特征。我曾经使用 new [] 删除[] ,但是到处都读到这是一个不好的做法。

我的问题是:在C ++中处理基于数组的数据结构的动态内存分配的正确方法是什么?

这是我所做的一个示例(该数组先前已由new []分配):

template <typename T>
void ArrayList<T>::pushBack(T item) 
{
    if (size < capacity) {  // if there's room in the array
        array[size] = item; // simply add the new item
    } else { // otherwise allocate a bigger array                   
        capacity *= 2;
        T *temp = new T[capacity];
        // copy elements from the old array to the new one
        for (int i = 0; i < size; ++i)
            temp[i] = array[i];
        delete [] array;
        temp[size] = item;
        array = temp;
    }
    ++size;
}

2 个答案:

答案 0 :(得分:1)

否,您仍然不需要newdelete。在C ++中仍然使用new的唯一原因是执行聚合初始化,std::make_unique不支持聚合初始化,而且您根本不需要delete

您的代码示例将变为:

template <typename T>
void ArrayList<T>::pushBack(T item) 
{
    if (size < capacity) {  // if there's room in the array
        array[size] = item; // simply add the new item
    } else { // otherwise allocate a bigger array                   
        capacity *= 2;
        auto temp = std::make_unique<T[]>(capacity);
        // copy elements from the old array to the new one
        for (int i = 0; i < size; ++i)
            temp[i] = array[i];
        temp[size] = item;
        array = std::move(temp);
    }
    ++size;
}

也可以通过交换两个部分来考虑:

template <typename T>
void ArrayList<T>::pushBack(T item) 
{
    if (size >= capacity) {  // if there's no room in the array, reallocate                 
        capacity *= 2;
        auto temp = std::make_unique<T[]>(capacity);
        // copy elements from the old array to the new one
        for (int i = 0; i < size; ++i)
            temp[i] = array[i];
        temp[size] = item;
        array = std::move(temp);
    }

    array[size] = item; // simply add the new item
    ++size;
}

进一步的改进:重新分配元素时要移动它们而不是复制它们,而是使用标准算法而不是手动的for循环。

答案 1 :(得分:0)

对于这个项目,我相信使用newdelete确实是适当的;我的数据结构老师使用完全相同的内存分配样式。看来,人们不赞成使用分配的内存的普遍原因是难以正确管理。重要的是要记住记住delete您不再使用的所有内存-不想手上有任何孤立的RAM!