我对析构函数有疑问。在下面的 main.cpp 中,如果我将 ht 定义为指针,程序运行良好。但是如果我将 ht 定义为一个对象,它就会抛出一个错误
“malloc:* 对象 0x7fff511a4b00 错误:未分配正在释放的指针 * 在 malloc_error_break 中设置断点进行调试"
我理解这个错误,我的解决方案是将 ht 定义为指针。
我的问题是我是否可以直接将ht定义为一个对象,如果可以,我应该如何修改类定义。
谢谢。
主要.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;
}
复制构造函数.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[] h_table;
,因为您没有在 Hash_Table
中新建任何内容。您的代码是未定义的行为。
你的测试没有崩溃的原因是因为你只 new ht
但没有 delete ht
Hash_Table<int> *ht;
ht = new Hash_Table<int>;
delete ht; // if you did ht, it still crashes
关于c++ - 在 C++ 中破坏结构数组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13263182/