创建对象指针数组 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5887615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating an array of object pointers C++
提问by SIMEL
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.
其中ants
定义为Ant **ants;
并且Ant
是一个类。
Will it work?
它会起作用吗?
回答by StackedCrooked
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);
回答by Erik
std::vector<Ant> ants(num_ants);
ants.resize(new_num_ants);
回答by Mark B
Do you really need to hold pointersto the items? If you can use objects by value, a far simpler approach is to use a vector: std::vector<Ant> ants(num_ants);
. Then not only do you not have to write looping, but you don't have to worry about memory leaks from raw pointers and other object management items.
你真的需要持有指向项目的指针吗?如果您可以按值使用对象,则更简单的方法是使用向量:std::vector<Ant> ants(num_ants);
。那么你不仅不必编写循环,而且不必担心原始指针和其他对象管理项的内存泄漏。
If you need object pointers to say satisfy an API you can still use vector
for the outer container and allocate the objects manually.
如果您需要对象指针来表示满足 API,您仍然可以将其vector
用于外部容器并手动分配对象。
struct CreateAnt
{
Ant* operator()() const { return new Ant; }
};
std::vector<Ant*> ants(num_ants); // Create vector with null pointers.
std::generate(ants.begin(), ants.end(), CreateAnt());
回答by James Kanze
std::vector<Ant*> ants( num_ants );
for ( int i = 0; i != num_ants; ++ i ) {
ants[i] = new Ant;
}
Or if you don't know how many in advance:
或者,如果您不知道提前多少:
std::vector<Ant*> ants;
while ( moreAntsNeeded() ) {
ants.push_back( new Ant );
}
On the other hand, I think you need to ask yourself whether
Ant
is an entity type or a value. If it's a value, you'll
probably want to skip the pointers and the dynamic allocation;
if it's an entity type, you'll have to consider the lifetime of
the object, and when and where it will be deleted.
另一方面,我认为您需要问自己
Ant
是实体类型还是值。如果它是一个值,您可能希望跳过指针和动态分配;如果是实体类型,则必须考虑对象的生命周期,以及何时何地将其删除。
回答by Dima
Yes that's the general idea. However, there are alternatives. Are you sure you need an array of pointers? An array of objects of class Ant
may be sufficient. The you would only need to allocate the array:
是的,这是一般的想法。但是,还有其他选择。你确定你需要一个指针数组吗?类的对象数组Ant
可能就足够了。您只需要分配数组:
Ant *ants = new Ant[num_ants];
In general, you should prefer using std::vector
to using an array. A vector can grow as needed, and it will handle the memory management for you.
通常,您应该更喜欢使用std::vector
而不是使用数组。向量可以根据需要增长,它会为您处理内存管理。
In the code you have posted, you would have to delete each element of ants
in a loop, and then delete the array itself, delete [] ant
. Keep in mind the difference between delete
and delete []
.
在您发布的代码中,您必须删除ants
循环中的每个元素,然后删除数组本身,delete [] ant
. 牢记之间的差异delete
和delete []
。
One more point, since array indices in C++ are 0-based, the following convention is used to iterate over the elements:
还有一点,由于 C++ 中的数组索引是从 0 开始的,因此使用以下约定来迭代元素:
for (i=0; i<num_ants; i++)
{
ants[i] = new Ant();
}
This makes code much more readable.
这使得代码更具可读性。