簡體   English   中英

通過指針在多個STL容器中更新對象

[英]Object update in multiple STL containers via pointers

我有一個名為Group的類:

class Group
{
    int id;
    string addr;
    set<int> members;
    ...
};

我有指向存儲在這些容器中的多個組的指針:

vector<Group*> grpVec
map<int, Group*> grpIdMap 
map<string, Group*> grpAdMap  

我存儲這樣的指針:

//create and populate group object pointer Group *grp
grpVec.push_back(grp)
grpIdMap.insert(std::pair<int,Group*>(grp->id, grp)) 
grpAdMap.insert(std::pair<string,Group*>(grp->addr, grp))

現在,我想更新一個組對象。 如果僅更新grpIdMap容器​​中的指針,那么所有其他容器中的相同對象指針是否會更新?

//Will this update the same pointer object in grpVec and grpAdMap?
grpIdMap.find(1)->second->members.insert(99) 

這種方法有什么問題嗎?

如果所有指針均指向同一個對象,則可以使用任何指針更改該對象。


讓我們從圖形上看一下:

+-------------------+
| pointer in vector | -----\
+-------------------+       \
                             \
+--------------------+        \     +---------------+
| pointer in one map | -------->--- | actual object |
+--------------------+        /     +---------------+
                             /
+----------------------+    /
| pointer in other map | --/
+----------------------+

這種方法將更新對象。 如果有任何指向該對象的指針(而不是其副本),則它們將獲得更新的信息。

我建議您停止使用原始指針,並在此處閱讀如何使用智能指針: 什么時候使用哪種指針?

而且我認為您應該看一看: http : //en.cppreference.com/w/cpp/memory/shared_ptr

PS在類中使用封裝。 其他對象不應該知道數據如何存儲在類中,而只需提供接口即可。

PPS如果您希望所有成員都公開,也許您想使用struct而不是class

它改變的是指針指向的對象的值,而不是指針的值。因此,只要所有指針都指向同一個對象,它將起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM