TV1989
TV1989

Reputation: 39

storing object references in map C++

I'm new to C++ and trying to figure out a good way to store object references in map or unordered_map.

I've tried map<Key&, Value&> and map<reference_wrapper<Key>, reference_wrapper<Value>> and I can make then work eventually but it looks very ugly and I'm sure bug-ridden.

I know I can use pointers instead but I don't want to allocate memory as I'll have to clean up after.

Anyone knows of a good and clean way to achieve this?

Upvotes: 2

Views: 1163

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

If you have a reference, then you have a "thing" that the reference refers to. Consequently, you can just as easily store a pointer to the same "thing" without the need to allocate any additional memory. Pointers don't require dynamic allocation.

That being said, storing a smart pointer would be simplest and cleanest unless you have real, measurable performance concerns. I worry about unclear object lifetimes and dangling references, in your design.

Upvotes: 2

Related Questions