简体   繁体   English

如何在C ++中删除非动态分配的数组?

[英]How can I delete a non-dynamically allocated array in C++?

The reason why I ask is because I am using a non-dynamically allocated array for my hashtable; 我问的原因是因为我在哈希表中使用了非动态分配的数组。 however, for my rehash function in my hashtable, I need to be able to change the size of my old array. 但是,对于哈希表中的rehash函数,我需要能够更改旧数组的大小。 How can I do this? 我怎样才能做到这一点?

如果要更改大小,则必须动态分配,最好使用std::vector

Short answer: you can't. 简短的答案:您不能。

A longer answer would introduce very dirty and os-dependent hacks. 更长的答案将引入非常肮脏且依赖于操作系统的黑客。

If you want to manually control the lifetime of memory, you need to use dynamic memory allocation. 如果要手动控制内存的生存期,则需要使用动态内存分配。 Non-dynamically allocated memory (statically allocated) will only be deallocated when the memory goes out of scope. 非动态分配的内存(静态分配)仅在内存超出范围时才被释放。 Since this memory lives in the object your managing, that memory only goes out of scope when the owning object in deallocated. 由于此内存位于您要管理的对象中,因此仅当释放拥有的对象时,该内存才会超出范围。

So you will need to dynamically allocate a buffer at construction then when resizing allocate a new buffer, copy the contents from the old buffer into the new buffer, delete the old buffer, then assign your object's internal pointer to the new buffer. 因此,您将需要在构造时动态分配一个缓冲区,然后在调整大小时分配一个新缓冲区,将内容从旧缓冲区复制到新缓冲区,删除旧缓冲区,然后将对象的内部指针分配给新缓冲区。 Something like: 就像是:

// allocate a new, bigger array
Cell* newBuff = new Cells[/*newSize*/];

// copy into the new array
for (i = 0; i < myBufferSize; ++i)
{
   newBuff[i] = myBuffer[i];
}
// delete the old array
delete myBuffer;
// point to the new array
myBuffer = newBuff;

Could you base your hash table on a std::vector instead of using manual memory allocation? 您能否将哈希表基于std::vector而不是使用手动内存分配? This will handle the dynamic array for you, and you can resize with a simple .resize : 这将为您处理动态数组,您可以使用简单的.resize调整大小:

myBuffer.resize(/*newSize*/)

There are dozens of ways to handle this out. 有很多方法可以解决这个问题。 Of course "deallocating" a memory that was not allocated on the heap - is the worst hack to imagine. 当然,“取消分配”未在堆上分配的内存是想象中最糟糕的事情。

I may suggest something like this: 我可能会建议这样的事情:

class MyClass
{
   TableEntry* m_pStaticTable[/* some size */];

   TableEntry* m_pActualTable;
   size_t m_nSize;

   MyClass()
      :m_pActualTable(m_pStaticTable)
      ,m_nSize(_countof(m_pStaticTable))
   {
   }

   ~MyClass()
   {
      if (m_pActualTable != m_pStaticTable)
         delete[] m_pActualTable;
   }

};

Assuming you have something like this: 假设您有这样的事情:

TableEntry table[max_table_size];

you are going to need a separate variable that indicates how much of the array you are actually using: 您将需要一个单独的变量,该变量指示您实际使用了多少数组:

size_t table_size = 0;

and then you just use that variable instead of trying to resize the actual array. 然后只使用该变量,而不是尝试调整实际数组的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM