Reputation: 1036
In one of my project I came across a situation where I want to create in-memory indices of objects. The primary index may use a different key and secondary indices would use some other elements as keys.
If I am using std::map
for primary index as
std::map<string, Object>
then which's the best way to store reference/pointer for the secondary index using another container (again std::map for instance considering all the Objects are unique) without making additional copies of the Object?
Using raw pointers or references which pose the risk of dangling pointers or references (I know that ideally when Object gets deleted from primary index, care should also be taken to remove it from secondary index but would the pointers/references in secondary indices invalidate when container for primary index adjust itself internally?)
std::map<string, const Object*>
std::map<string, std::shared_ptr<Object>> // primary index
std::map<string, std::weak_ptr<Object>> // secondary index
I know there are pros and cons for both the approaches. Especially I don't want to lose the flexibility of directly inserting the objects in the primary container but I also do not want the secondary index to copy the Objects again. The difficulty in using smart pointers just for secondary index is that they would not own the Object.
Thanks in advance for help.
Upvotes: 1
Views: 221
Reputation: 16156
Place your objects in some container. Depending on the frequency of additions / deletions of objects you may want to consider using a container that does not invalidate references to its elements, like a std::list
or a std::deque
.
Then, for your maps, just reference the objects (or any of their members) using references, i.e. using std::reference_wrapper
.
Encapsulate the backend storage as well as the indices so that whenever you add or remove objects you remove invalid references from the indices as well as add any new references.
That way you only have to store your objects once and get around using smart pointers. This will obviously only work if you actually own the objects and control their lifetimes, and if you can keep the indices encapsulated (in order to keep them updated).
Upvotes: 1