Note that there are some explanatory texts on larger screens.

plurals
  1. POStoring struct instances in a std::map
    text
    copied!<p>I'm trying to map some structs to some other instances, like this:</p> <pre><code>template &lt;typename T&gt; class Component { public: typedef std::map&lt;EntityID, T&gt; instances_map; instances_map instances; Component() {}; T add(EntityID id) { T* t = new T(); instances[id] = *t; return *t; }; }; </code></pre> <p>Then I use it like this:</p> <pre><code>struct UnitInfos { int owner_id; int health; float x, y; }; class LogicComponent : public Component&lt;UnitInfos&gt; {}; </code></pre> <p>The problem is that when it later retrieve data later on, like this:</p> <pre><code>comp.instance[id]; </code></pre> <p>I get a breand new object with properties initialized at default values. </p> <p>Is there something inherently wrong with this piece of code, or am I leaving out information about the problem?</p> <hr> <p>As per @aaa suggestion, i change the code to </p> <pre><code>typedef std::map&lt;EntityID, T&gt; instances_map; instances_map instances; T&amp; add(EntityID id) { instances[id] = T(); return instances[id]; }; </code></pre> <p>but when I access it</p> <pre><code>UnitInfos &amp;info = logic_c.instances[id]; </code></pre> <p>the value of info.x is still 0. Any pointers?</p> <hr> <p>The problem was how I stored the reference to LogicComponent in another class. using <code>LogicComponent logic_c;</code> instead of <code>LogicComponent&amp; logic_c;</code>. It now works, but I'm storing pointers in the map (instead of @aaa's suggestion). Is this a bad idea?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload