title: Creating a vector of all instances of a class when objects are being instantiated in a loop?
body: <p>I am trying to keep a pointer to all of the instances of a class inside of a static member variable.</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class Person {
  public:
    static std::vector&lt;Person*&gt; allPeople;
    int age;
    Person(int a) {
      age = a;
      allPeople.push_back(this);
    }
  };
  
  std::vector&lt;Person*&gt; Person::allPeople;
  
  
  int main() {
    static std::vector&lt;Person&gt; children;
  
    for(int i=0;i&lt;10;i++) {
      children.push_back(Person(i));
    }
  
    for(int i=0;i&lt;Person::allPeople.size();i++) {
      std::cout &lt;&lt; Person::allPeople[i]-&gt;age;
    }
  
    return 0;
  }
  </code></pre>
  <p>Right now, this code has 10 instances of the same object stored inside <code>Person::allPeople</code>. I think that it has to do something with how every time it loops around, the object goes out of scope. One of my solutions would be to make copies of the object and add pointers to those, except  in my actual code, the objects' values would be changing frequently. If anyone knows what the best solution is please let me know, sorry if this is a bit of a messy question I can clarify if needed.</p>