带有指针的结构体向量
C++ vector of structs with pointers
我试图创建一个结构体向量,每个结构体都有一个指针数组。然而,我似乎不能在没有内存问题的情况下删除向量。
运行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
添加一个复制构造函数,它将复制整个数组
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 如何使用结构体的向量数组?
- 如何使用迭代器指向结构体c++的向量
- 创建结构体向量,表达式:向量下标超出范围
- C++ push_back() 一个结构体到一个向量中
- 使用 boost::p ython,如何将结构体向量作为字典列表返回给 Python
- 交换结构体 c++ 向量的内容
- Vector::erase()也擦除结构体的成员向量
- 如何在结构体中传递指向CURL的指针到向量
- 对的向量和包含两个元素的结构体的向量的内存布局的区别- c++ /STL
- 列表排序和结构体向量排序之间的性能差距.c++
- 带有指针的结构体向量
- 结构体向量的问题:解约束迭代器(可能很容易)
- 试图使用指向结构体向量的指针访问结构体类型时出错
- 如何在结构体向量的ROS中发布消息?
- c++中初始化结构体向量的正确方法
- 使用命令行参数创建结构体向量
- c++结构体向量的适当方法
- 结构体向量与结构体向量的映射
- 从文本文件c++中加载结构体向量的奇怪问题