[英]How to add pointers into a pointer to a vector
我有這個:
std::vector<Pair *> *artistAttributes;
其中Pair
是一個類,如何將元素添加到此指針中?
如果它只是一個像這樣的std::vector
,我知道如何訪問它,
std::vector<Pair *> artistAttributes;
但是我不熟悉如何向其中添加元素,因為我對指針非常陌生。
我很懂指點。
僅指向自動存儲(“堆棧”)上的對象的指針和指向自由存儲(“堆”)上的對象的指針之間存在語義差異,因為必須在某個時候使用指向堆上對象的指針釋放( delete
/ delete[]
)之前用new
(或new[]
)分配的內存。
這不僅容易被遺忘,而且在分配和釋放之間拋出異常時也無法完成。 為了更簡單,發明了遵循RAII/RDID 慣用語(“資源獲取是初始化/資源銷毀是刪除”)的智能指針:原始指針被封裝在管理它們處理的資源的生命周期的對象中。
這使得在許多情況下可以避免遵循3/5 規則(這更像是現代 C++ 中的四大(半)規則),而是使用零規則。
此外,擁有指向std::vector<>
的指針也沒有實際意義,因為向量復制起來很便宜(與必須管理動態分配的內存的不便相比)。
所以代替
std::vector<Pair *> *artistAttributes;
更好地使用
std::vector<std::shared_ptr<Pair>> artistAttributes;
看到這個:
std::vector<Pair*> *artistAttributes;
artistAttributes = new std::vector<Pair*>;
artistAttributes->push_back(new Pair())
...
for(int i=0; i<artistAttributes->size(); i++)
delete (*artistAttributes)[i] // Don't forget
delete artistAttributes; // Don't forget
相比之下:
std::vector<Pair*> artistAttributes;
//artistAttributes = new std::vector<Pair*>; // no needed
artistAttributes.push_back(new Pair()) // use . instead of ->
...
for(int i=0; i<artistAttributes.size(); i++)
delete artistAttributes[i] // Don't forget
並與:
std::vector<Pair> artistAttributes;
//artistAttributes = new std::vector<Pair*>; // no needed
artistAttributes.push_back(Pair())
通常,您使用.
操作員。 如果要訪問指向對象的指針的成員,請改用->
運算符。
因此,您可以使用artistAttributes->push_back()
(添加新元素)或artistAttributes->at()
(修改現有元素)修改向量。 同樣,您也可以執行(*artistAttributes).push_back()
和(*artistAttributes).at()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.