Chadwick Robbert
Chadwick Robbert

Reputation: 1036

What's the best way of sharing object across containers?

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?

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

Answers (1)

Daniel Jour
Daniel Jour

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

Related Questions