title: How do I handle an object moving in memory in the middle of a method?
body: <p>I'm writing a VM in C++ for a programming language. The language is garbage collected, so I have instances of C++ classes that are allocated in the garbage collected heap. I'm using a copying collector, so when a GC happens, those objects are moved in memory. This means every pointer to that object needs to be updated. <em>Most</em> of those pointers are easy to handle, except for one tricky one: <code>this</code>. Consider:</p>
  
  <pre><code>class SomeObj : public Managed      // inheriting from this means it's on the GC heap
  {
  public:
    void method()
    {
      SomeObj* other = new SomeObj(); // could trigger a GC.
      printf("%d\n", someField);      // this points to wrong memory
    }
  
  private:
    int someField;
  };
  </code></pre>
  
  <p>If I am in the middle of an instance method of some object that lives on the GC heap, then <code>this</code> points to some GC memory. A collection can occur in the middle of this method. When that happens, the object gets moved to a new location. But, since we are in the middle of a method call, <code>this</code> is still pointing to the old wrong location.</p>
  
  <p>I could get around this by not using instance methods on classes that are in managed memory, but I do like that the code is simpler this way. Are there any techniques for dealing with this?</p>