[英]creating an array of object pointers C++
我想創建一個數組來保存指向許多 object 的指針,但是我事先不知道我將保存的對象數量,這意味着我需要為數組動態分配 memory。 我想到了下一個代碼:
ants = new *Ant[num_ants];
for (i=1;i<num_ants+1;i++)
{
ants[i-1] = new Ant();
}
其中ants
定義為Ant **ants;
Ant
是 class。
它會起作用嗎?
它會起作用嗎?
是的。
但是,如果可能,您應該使用向量:
#include <vector>
std::vector<Ant*> ants;
for (int i = 0; i < num_ants; ++i) {
ants.push_back(new Ant());
}
如果您必須使用動態分配的數組,那么我更喜歡這種語法:
typedef Ant* AntPtr;
AntPtr * ants = new AntPtr[num_ants];
for (int i = 0; i < num_ants; ++i) {
ants[i] = new Ant();
}
但是忘記這一切。 該代碼仍然沒有任何好處,因為它需要手動 memory 管理。 要解決此問題,您可以將代碼更改為:
std::vector<std::unique_ptr<Ant>> ants;
for (auto i = 0; i != num_ants; ++i) {
ants.push_back(std::make_unique<Ant>());
}
最重要的是:
std::vector<Ant> ants(num_ants);
std::vector<Ant> ants(num_ants);
ants.resize(new_num_ants);
你真的需要持有指向項目的指針嗎? 如果您可以按值使用對象,則更簡單的方法是使用向量: std::vector<Ant> ants(num_ants);
. 那么您不僅不必編寫循環,而且您不必擔心來自原始指針和其他 object 管理項的 memory 泄漏。
如果您需要 object 指針來表示滿足 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());
std::vector<Ant*> ants( num_ants );
for ( int i = 0; i != num_ants; ++ i ) {
ants[i] = new Ant;
}
或者,如果您不知道提前多少:
std::vector<Ant*> ants;
while ( moreAntsNeeded() ) {
ants.push_back( new Ant );
}
另一方面,我想你需要問問自己Ant
是實體類型還是值。 如果它是一個值,您可能希望跳過指針和動態分配; 如果它是實體類型,則必須考慮 object 的生命周期,以及何時何地將其刪除。
是的,這是一般的想法。 但是,還有其他選擇。 你確定你需要一個指針數組嗎? class Ant
的對象數組可能就足夠了。 您只需要分配數組:
Ant *ants = new Ant[num_ants];
通常,您應該更喜歡使用std::vector
而不是使用數組。 向量可以根據需要增長,它將為您處理 memory 管理。
在您發布的代碼中,您必須在循環中刪除 ant 的每個元素,然后刪除數組本身, delete [] ant
ants
請記住delete
和delete []
之間的區別。
還有一點,由於 C++ 中的數組索引是從 0 開始的,因此使用以下約定來迭代元素:
for (i=0; i<num_ants; i++)
{
ants[i] = new Ant();
}
這使代碼更具可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.