Kevin Kostlan
Kevin Kostlan

Reputation: 3519

C++ memory management for a vector with variable length items

Take a variable length struct (if this were a real program, an int array would be better):

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

(...)

And build a vector out of it:

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[]

(...)

The above works for g++ in ubuntu. The new() calls are needed to avoid segfaults. Can the lst vector be deleted all at once when it is no longer needed, or will the new calls cause a memory leak? It would be tedious to manually delete() all of the parts called with new().

Upvotes: 1

Views: 356

Answers (3)

Puppy
Puppy

Reputation: 146910

Why not just use a vector of vector of int? That's it's job. You should not be calling new outside of a dedicated class.

Upvotes: 2

Kristopher Johnson
Kristopher Johnson

Reputation: 82535

The typical ways to do this in C++ would be to define constructors and destructors and assignment operators for the list_of_numbers struct that take care of the memory management, or (much better) use a std::vector<int> for the numbers field and get rid of the length field.

But if you do that, you may as well get rid of the struct entirely, and just do this:

#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

Upvotes: 4

ezpz
ezpz

Reputation: 12037

In general, you would want to put cleanup code in the destructor of the object (~list_of_numbers()) and memory creating code in the constructor (list_of_numbers()). That way these things are handled for you when the destructor is called (or when the object is created).

Upvotes: 0

Related Questions