堆栈分配的结构总是在同一个位置?
Stack allocated struct always in the same location?
我正在为散列编写一个插入函数 table,我需要在该函数中创建一个键值对(结构项)。我发现如果我在堆栈上创建它,例如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 是堆栈分配的,我使用它的方式在评论中。
堆栈分配版本不起作用,因为您正在存储指向局部变量的指针,该变量稍后会超出范围。您在对象本身的生命周期之后保留指针。
我正在为散列编写一个插入函数 table,我需要在该函数中创建一个键值对(结构项)。我发现如果我在堆栈上创建它,例如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 是堆栈分配的,我使用它的方式在评论中。
堆栈分配版本不起作用,因为您正在存储指向局部变量的指针,该变量稍后会超出范围。您在对象本身的生命周期之后保留指针。