【问题标题】:C++ vector of structs with pointers带有指针的结构的 C++ 向量
【发布时间】:2013-05-30 11:48:16
【问题描述】:

我正在尝试创建一个结构向量,每个结构都有一个指针数组。但是,如果没有内存问题,我似乎无法删除向量。

当我运行 valgrind 时

==29801== 无效的 free() / delete / delete[] / realloc() ==29801== 在 0x4A05A36:操作员删除 (vg_replace_malloc.c:515) ==29801== by 0x4009D4: test_struct::~test_struct() (在/home/hltcoe/rcotterell/code-switching/a.out) ==29801== by 0x40142B: void std::_Destroy(test_struct*) (in /home/hltcoe/rcotterell/code-switching/a.out) ==29801== by 0x401299: void std::_Destroy_aux::__destroy(test_struct*, test_struct*) (在/home/hltcoe/rcotterell/code-switching/a.out)

编辑

#include <vector>
using namespace std;

struct test_struct {
  public:
    int * array;
    test_struct() {
       array = NULL;
    }
    ~test_struct() {
       delete[] array;
    } 
   private:
     test_struct(const test_struct& that);
     test_struct& operator=(const test_struct& that);
};

int main(int argc, char ** argv) {

  vector <test_struct> data;

  for (int i = 0; i < 5; ++i) {
       test_struct tmp;
       tmp.array = new int[5];
       data.push_back(tmp);
   }
}

它给出了以下编译错误。有什么想法吗?

【问题讨论】:

标签: c++ pointers vector valgrind destructor


【解决方案1】:

您应该关注rule of three 或尽可能使用 STL 容器:

struct test_struct 
{
  explicit test_struct(int size) : array(size) { }    
  std::vector<int> array;
};


int main()
{
  vector <test_struct> data(5, test_struct(5));

  return 0;
}

【讨论】:

    【解决方案2】:

    由于test_struct 析构函数以及您尝试将结构存储在vector 中的事实,您的解决方案不起作用。
    test_struct tmp 被推送到向量时,会创建test_struct 的副本。然后tmp 被调用delete[] array 销毁,vector &lt;test_struct&gt; data 中的副本以悬空指针结束。
    您可能需要重新考虑您的架构,或者至少为 test_struct 添加一个复制构造函数,它将复制整个数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2012-08-17
      • 2012-02-07
      • 1970-01-01
      • 2018-08-28
      相关资源
      最近更新 更多