title: Read Access Violation From Using Smart Pointers
body: <p>This problem has bugged me for several days now, and I just cant figure it out. What I am trying to do is get an Entity from the entityMap and make a copy of it. An Entity is essentialy a map of components, so I looped through each component and made a copy of it. I debugged the program, and it worked fine until the very last line, where it said "read access violation <strong>this</strong> was 0xFFFFFFFFFFFFFFF7." It was very strange as everything was initialized (I checked the debugger)</p>
  
  <pre><code>if (entityMap.find(classname) != entityMap.end()) {
      std::shared_ptr&lt;Entity&gt; &amp; prefab = entityMap[classname];
      std::shared_ptr&lt;Entity&gt; entity = std::shared_ptr&lt;Entity&gt;(new Entity());
      for (auto &amp; component : prefab-&gt;GetComponentMap()) {
          Component * compPtr = component.second.get();
          std::cout &lt;&lt; compPtr-&gt;GetMemorySize() &lt;&lt; "\n";
          size_t size = sizeof(compPtr-&gt;GetMemorySize());
          void * buffer = operator new(size);
          memcpy(buffer, compPtr, size);
          std::shared_ptr&lt;Component&gt; newComponent = std::shared_ptr&lt;Component&gt;(reinterpret_cast&lt;Component *&gt;(buffer));
          entity-&gt;AddComponent(newComponent);
          newComponent-&gt;SetOwner(entity);
      }
  </code></pre>
  
  <p>Here is the offending line</p>
  
  <pre><code> newComponent-&gt;SetOwner(entity);
  </code></pre>
  
  <p>Here is all it does, setting the owner instance variable to the passed in parameter. That was where the debugger complained and sent me to file "memory" at _Decref method.</p>
  
  <pre><code>void Component::SetOwner(std::shared_ptr&lt;Entity&gt; owner) {
      this-&gt;owner = owner;
  }
  </code></pre>