views:

76

answers:

2

I have a data structure that stores ... well, data. Now, I need to access various pieces of data in slightly different manner, so I'm essentially building an in-memory index. But I'm wondering: should the index hold pointers or copies?

To elaborate, say I have

class Widget
{
    // Ways to access the list of gears...
private:
    std::list<Gears> m_gears;
};

Now, I have two Widgets, and there exists between these two a mapping between their Gears. Currently, this is

boost::unordered_map<Gear, Gear>

but Gear is a fairly hefty class, and I feel like making so many copies is poor design. I could store a pointer, but then the mapping is only valid for the lifetime of the corresponding Widgets, and you start getting ->s... (And if that std::list ever changes to a std::vector, it gets more complex...)

Pertaining to the copies, it's actually slightly worse: There's two boost::unordered_maps, one for each direction. So, for each Gear, I'm making up to 2 copies of it.

Alternatively, I could put the index inside the Widget class, but I feel like this violates the responsibilities of the Widget class.

A: 

You might try Boost Pointer Container Library: http://www.boost.org/doc/libs/1_43_0/libs/ptr_container/doc/ptr_container.html

I think it addresses exactly the problem you are facing.

dark_charlie
My understanding of the Boost Pointer Containers is that they owned the objects inserted into them. My objects are actually on the stack, and thus, do not need `delete` called on them. I might still look into this to see if there's a way to use it without it deleting its contents.
Thanatos
A: 

Could you store all gears in one place, like statically in the gears class, and then have each mapping AND widget store only the reference/index to it?

You would have to keep track of references to each gear so you know when you can dispose them, but that should be easy enough.

Willfulwizard
This sounds like a flyweight -- is that what you mean?
Thanatos
Yes, that sounds like what I was describing. (Thank you, I had not heard the term before.) Since you have, does it not solve your problem?
Willfulwizard