c++ - Define a custom map using smart pointers or reference wrapper -


i've struct follows:

struct t_my_toy {    uint32_t id;    float data; }; 

i define custom map. first implementation was:

typedef std::map<uint32_t, t_my_toy*> t_my_toy_map; 

is correct use, instead of t_my_toy*, smart pointer or reference wrapper?

typedef std::map<uint32_t, std::shared_ptr<t_my_toy> > t_my_toy_map; 

or:

typedef std::map<uint32_t, std::reference_wrapper<t_my_toy> > t_my_toy_map; 

which best solution?

nearly always, best option store objects.

only store pointers or references if there's reason to: either because objects aren't owned container, or because of multiple polymorphic types.

in first case, container doesn't own objects. if can guarantee objects won't destroyed while still in container, store raw pointers. otherwise, need safe shared-ownership semantics storing shared_ptr or weak_ptr.

in second case, container own objects. single ownership semantics best managed unique_ptr; although shared_ptr might necessary if need share ownership.

reference wrappers used when need type acts object rather pointer (i.e. doesn't need explicit dereferencing); they're typically used templates expect object types. there's no need when you're controlling how interact elements; using them rather raw pointers potential cause mild confusion hiding indirection. since don't manage objects' lifetimes, used in situations use raw pointers.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -