如何释放 new[] 分配的内存?

How to free memory allocated by new[]?

我目前正在尝试创建类似矢量的容器。它使用由 new[] 分配的内存作为基础。当我需要扩展数组时,问题就出现了。我用 new[] 分配了更大的内存块,然后 memcpy 旧内存和 delete[] 旧内存。问题是,试图在其中存储任何指针或任何包含指针的对象会导致内存损坏。所以我需要一种方法来释放使用的内存而不破坏内部的对象

编辑:一些理解问题的代码:

template<typename T>
class myvector
{
private:
 T* _data;
 size_t _size, _capacity;
 static constexpr float multiplier = 1.5;
public:

void expand()
{
    size_t e_size = sizeof(T);
    size_t old_capacity = this->_capacity;
    this->_capacity = (unsigned long)(float(this->_capacity) * myvector::multiplier);
    T *tmp = new T[this->_capacity];
    memcpy(tmp, this->_data, e_size * (old_capacity));
    // this will destroy all the objects inside the container
    // which will result in destruction of any allocated memory
    delete[] this->_data; 
    // so now we have an array of invalid pointers. fun time
    this->_data = tmp;
}
}

How to free memory allocated by new[]?

使用delete[]。这必须在指针值丢失之前完成,并且必须在最后一次使用指针值之后完成。而且它必须恰好完成一次。并且除了数组 new.

返回的指针外,不得对任何其他指针执行此操作

Thing is, trying to store any pointer or any pointer-containing object inside result in memory corruption.

那么您使用这些对象的方式就存在一个错误。在模板中存储此类对象本身应该不是问题。

So I need a way to free the memory used without destroying objects inside

那根本不可能。没有存储就不能存在对象(除了不适用此处的特殊情况)。

delete[] this->_data; 
// so now we have an array of invalid pointers. fun time

为什么会有无效指针数组?数组中的指针是否指向this->_data?

确实,您的数据结构没有其元素的稳定地址。扩展将使对元素的任何引用无效。如果你需要这样的稳定​​性,那么你必须使用基于节点的数据结构,例如链表。


您的模板确实有一个限制,即它仅针对可简单复制的内容进行了明确定义 类。也许您忽略了这个限制。摆脱这个限制很容易:只需使用 std::copy(或者 <algorithm> 中的 std::move,具体取决于您需要的异常安全保证)而不是 std::memcpy。 =22=]