Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an array of object pointers C++

I want to create an array that holds pointers to many object, but I don't know in advance the number of objects I'll hold, which means that I need to dynamically allocate memory for the array. I have thought of the next code:

ants = new *Ant[num_ants];
for (i=1;i<num_ants+1;i++)
{
    ants[i-1] = new Ant();
}

where ants is defined as Ant **ants; and Ant is a class.

Will it work?

like image 234
SIMEL Avatar asked May 04 '11 17:05

SIMEL


2 Answers

Will it work?

Yes.

However, if possible, you should use a vector:

#include <vector>

std::vector<Ant*> ants;
for (int i = 0; i < num_ants; ++i) {
    ants.push_back(new Ant());
}

If you have to use a dynamically allocated array then I would prefer this syntax:

typedef Ant* AntPtr;
AntPtr * ants = new AntPtr[num_ants];
for (int i = 0; i < num_ants; ++i) {
    ants[i] = new Ant();
}

But forget all that. The code still isn't any good since it requires manual memory management. To fix that you could to change your code to:

std::vector<std::unique_ptr<Ant>> ants;
for (auto i = 0; i != num_ants; ++i) {
    ants.push_back(std::make_unique<Ant>());
}

And best of all would be simply this:

std::vector<Ant> ants(num_ants);
like image 185
StackedCrooked Avatar answered Oct 27 '22 01:10

StackedCrooked


std::vector<Ant> ants(num_ants);
ants.resize(new_num_ants);
like image 36
Erik Avatar answered Oct 27 '22 02:10

Erik