title: How to Convert beween Stack and Heap Objects
body: <p>Example:</p>
  
  <pre><code>Class *_obj1;
  Class *_obj2;
  
  void doThis(Class *obj) {}
  
  void create() {
      Class *obj1 = new Class();
      Class obj2;
  
      doThis(obj1);
      doThis(&amp;obj2);
  
      _obj1 = obj1;
      _obj2 = &amp;obj2;
  }
  
  int main (int argc, const char * argv[]) {
  
      create();
  
      _obj1-&gt;doSomething();
      _obj2-&gt;doSomething();
  
      return 0;
  }
  </code></pre>
  
  <p>This creates 2 objects, creates pointers to them, then main() calls a method on each. The Class object creates a char* and stores the C string "Hello!" in it; the ~Class() deallocator frees the memory. The doSomething() method prints out "buff: %s" using printf(). Simple enough. Now if we run it we get this:</p>
  
  <blockquote>
    <p>Dealloc<br>
    Buff: Hello!<br>
    Buff: ¯ø_ˇ</p>
  </blockquote>
  
  <p>Obviously the stack object <em>does not work here</em> - it's obvious that when the function exits the pointer _obj2 is pointing at a location in the stack. This is why I used heap objects in my previous question, which people told me was "stupid".</p>
  
  <p>So, the first question is: if <strong>how can I convert the stack object (obj2) to a heap object so it's not deallocated after create() exits?</strong> I want a straight answer, not an arrogant "you're doing it wrong" as so many have done. Because in this case stack objects cannot work so heap objects seem to be the only way. EDIT: Also, converting back to a stack object would be useful as well.</p>
  
  <p>The second question: the specific example of heap objects being "wrong" was creating a new <code>vector&lt;string&gt;*</code> using the <code>new</code> operator. <strong>If dynamically allocating STL objects is wrong, then what's the right way?</strong> Obviously if you create them as stack objects it fails because they're immediately deallocated, but I've been told (again, by a very high-ranking member) that dynamically allocating them can corrupt the heap. So what's the right way to do it?</p>