我有一個關於析構函數的問題。在下面的main.cpp中,如果我將ht定義爲一個指針,程序工作正常。但是,如果我定義高程作爲一個對象,它會拋出一個錯誤在C++中破壞struct array成員
「的malloc:*錯誤對象0x7fff511a4b00:被釋放的指針沒有被分配 *設置malloc_error_break斷點調試」
我理解這個錯誤,我的解決方案是將ht定義爲指針。
我的問題是我是否可以直接定義ht作爲對象,如果答案是肯定的,我應該如何修改類定義。
謝謝。
的main.cpp
#include "copy_constructor.h"
int main()
{
// Define ht as pointer works fine
//Hash_Table<int> *ht;
//ht = new Hash_Table<int>;
Hash_Table<int> ht;
// keyed_structure<int> s;
// s.data_val = 10;
return 0;
}
copy_constructor.h
#ifndef COPY_CONSTRUCTOR_H
#define COYP_CONSTRUCTOR_H
#include <cstdlib>
#include <iostream>
const size_t MAX_SIZE = 3;
template<class D> struct keyed_structure
{
size_t key_val;
D data_val;
bool empty_val;
};
template<class D> class Hash_Table
{
public:
// COnstructor
Hash_Table() {
//h_table = new keyed_structure<D> [MAX_SIZE];
for (size_t index=0; index < MAX_SIZE; ++index) {
h_table[index].empty_val = true;
}
}
// Destructor
~Hash_Table() {
//std::cout << "Do destruct" << std::endl;
delete[] h_table;
}
private:
keyed_structure<D> h_table[MAX_SIZE];
};
#endif
這樣做對你沒有使用'delete []'的不確定行爲。 – chris
@chris感謝您快速回復我的問題。你是什麼意思「沒有使用delete []」的未定義行爲? – mitchelllc
把'['''''''''''''''''''''刪除掉。默認的析構函數正確地執行它。 – chris