具有可变长度项的向量的C ++内存管理

时间:2010-08-09 00:09:21

标签: c++ memory-management vector struct

采用可变长度的结构(如果这是真正的程序,int数组会更好):

#include <vector>
struct list_of_numbers(){
  int length;
  int *numbers; //length elements.
};
typedef std::vector<list_of_numbers> list_nums; //just a writing shortcut

(...)

用它构建一个向量:

list_nums lst(10); //make 10 lists.
lst[0].length = 7; //make the first one 7 long.
lst[0].X = new int[7]; //allocate it with new[]

(...)

以上适用于ubuntu中的g ++。需要new()调用来避免段错误。可以在不再需要时立即删除lst向量,还是新调用会导致内存泄漏?手动删除()使用new()调用的所有部分将会很繁琐。

3 个答案:

答案 0 :(得分:4)

在C ++中执行此操作的典型方法是为负责内存管理的list_of_numbers结构定义构造函数和析构函数以及赋值运算符,或者(更好)使用std::vector<int> numbers字段并删除length字段。

但是如果你这样做,你也可以完全摆脱结构,只需这样做:

#include <vector>
typedef std::vector<int> list_ints;
typedef std::vector<int_ints> list_lists;

(...)

list_lists lst(10); // make 10 lists.
lst[0].resize(7);   // set length of the zeroth list to 7

答案 1 :(得分:2)

为什么不使用int的向量向量?这是它的工作。你不应该在专门的课堂之外打电话给新人。

答案 2 :(得分:0)

通常,您希望将清理代码放在对象(~list_of_numbers())的析构函数中,并在构造函数(list_of_numbers())中创建内存。这样就可以在调用析构函数时(或者在创建对象时)为您处理这些事情。