title: C++ vector objects going out of scope
body: <p>I'm having trouble understanding how to properly build a vector of pointers (I'm pretty new to C++). I think the following code summarizes the problem:</p>
  
  <p><strong>Mok.h</strong></p>
  
  <pre><code>class Mok
  {
  public:
      Mok(int n) : m_num{n}
      int getNum() {return m_num}
  private:
      int m_num;
  };
  </code></pre>
  
  <p><strong>Bar.h</strong></p>
  
  <pre><code>class Bar
  {
  public:
      Bar();
  
      void setTiles();
      void printTiles();
  
  private:
      std::vector&lt;Mok*&gt; m_tileSet;
  };
  </code></pre>
  
  <p><strong>Bar.cpp</strong></p>
  
  <pre><code>void Bar::setTiles()
  {
      for (int i = 0; i &lt; 4; ++i)
      {
          m_tileSet.push_back(&amp;Mok(i));
      }
  }
  
  void Bar::printTiles()
  {
      for (const auto &amp;mok : m_tileSet)
      {
          std::cout &lt;&lt; mok-&gt;getNum() &lt;&lt; " ";
      }
  }
  </code></pre>
  
  <p>The idea would be to print the numbers stored in the vector, but instead I get crazy numbers (I know it doesn't make much sense for ints, the real code is more complex, this is a simplification. Imagine Mok as a big object, and the vector containing thousands of objects). Inside <em>setTiles()</em> everything seems to get stored ok (VS debugger says so), but when I get to <em>printTiles()</em>, the information is lost and I get numbers like <em>-858993460</em>.</p>
  
  <p>I guess the Mok objects are going out of scope, so the references (edit: I mean addresses) start pointing nowhere? What would be the way to do this?</p>
  
  <p>Thanks! :)</p>