c++ - 在 C++ 中破坏结构数组成员

标签 c++ destructor

我对析构函数有疑问。在下面的 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/

相关文章:

c++ - 如何为现有对象填充接口(interface)?

C++ 结构填充和字段打包

c++ - 将成员变量保存为智能指针和显式定义析构函数的重要性

c++ - 如果包含析构函数,类的大小会增加

c++ - 如何将析构函数专门用于一种情况或某些情况?

c++ - 谷歌模拟 : Mocking parent class?

c++ - 使用 2D 指针时出错

c++11 - move 语义 : why is the destructor called on the moved instance and is that a problem?

c++ - qt 应用程序和 std::shared_ptr

c++ - 此代码中调试断言的原因