堆栈分配结构总是在同一位置

Stack allocated struct always in the same location?

本文关键字:位置 分配 结构 堆栈      更新时间:2023-10-16

我正在为哈希表编写插入函数,我需要在该函数中创建一个键值对(struct Item)。我发现,如果我在堆栈上创建它,例如Item item(key, value);,那么每次当我调用Insert时,不同的键值对将在堆栈上的相同位置创建。如果我使用堆分配内存,就不会发生这种情况。为什么它们在堆栈上的位置相同?

下面是我的示例代码:
void Insert (int key, int value) {
int hash_value = Hash(key);
if (hash_value >= table.size() || hash_value < 0) {
  throw std::out_of_range("Cannot insert.");      
} else {
  Item *item = new Item(key, value);  // This will work
  // Item item2(key, value); This does not work
  if (!table[hash_value]) {  // there is not item in this cell
    Cell *c = new Cell(0, item);  // Cell *c = new Cell(0, &item2)
    table[hash_value] = c;
  } else {  // try next one, if occupied, the one after ...
    int index = hash_value + 1;
    while (table[index]) {
      ++index;
      if (index == table.size()) {
        index = 0;
      } else if (index == hash_value) {
        throw std::out_of_range("Opps! The table is full! Cannot insert!");
      }
    }
    Cell *c = new Cell(0, item);  // Cell *c = new Cell(0, &item2)
    table[index] = c;
  }
}

}

Item2是堆栈分配的,我使用它的方式在注释中。

堆栈分配的版本不起作用,因为您存储的是指向局部变量的指针,该指针稍后会超出作用域。