创建一个对象指针数组C ++ [英] creating an array of object pointers C++

查看:312
本文介绍了创建一个对象指针数组C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个数组来保存指向很多对象的指针,但我不知道预先保存的对象数量,这意味着我需要为数组动态分配内存。我想到了下面的代码:

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

其中 ants 定义为 Ant ** ants; Ant 是一个类。


$ b

解决方案


它会工作吗?


是的。



但是,如果可能,您应该使用向量:

  #include< vector> 

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



如果你必须使用动态分配的数组,

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

但忘记了。代码仍然没有任何好处,因为它需要手动内存管理。要解决此问题,您可以将代码更改为:

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

最好的一点是:

  std :: vector< Ant>蚂蚁(num_ants); 


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?

解决方案

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);

这篇关于创建一个对象指针数组C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆