带有指针的结构体向量

C++ vector of structs with pointers

本文关键字:结构体 向量 指针      更新时间:2023-10-16

我试图创建一个结构体向量,每个结构体都有一个指针数组。然而,我似乎不能在没有内存问题的情况下删除向量。

运行valgrind

==29801== Invalid free()/delete/delete[]/realloc()==29801== at 0x4A05A36: operator delete (vg_replace_mallocc:515)==29801== 0x4009D4: testrongtruct::~testrongtruct() (in/home/htcoe/rcotterell/code-switching/a.o out)==29801== by 0x40142B: void std::_Destroy(testrongtruct*) (in/home/hltcoe/rcotterell/code-switching/a.o ut)==29801== 0x401299: void std::_Destroy_aux::__destroy(testrongtruct*,Testrongtruct *)(在/home/htcoe/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);
   }
}

并给出以下编译错误。什么好主意吗?

您应该遵循三个规则或尽可能使用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;
}

您的解决方案不起作用,因为test_struct析构函数和您试图将结构体存储在vector中的事实。
test_struct tmp被推入向量时,将创建test_struct的副本。然后通过调用delete[] array来销毁tmp,并且vector <test_struct> data中的副本以悬空指针结束。
您可能需要重新考虑您的架构,或者至少为test_struct添加一个复制构造函数,它将复制整个数组