Casting to an object with pointers
<p>I have a class, <code>Fixture</code>, that I want to cast to a 3rd party library class, <code>b2FixtureDef</code>.  Currently, my function looks like this:</p>

<pre><code>Fixture::operator b2FixtureDef() const {
    b2FixtureDef fd;
    fd.density = m_density;
    fd.friction = m_friction;
    fd.isSensor = m_isSensor;
    fd.restitution = m_restitution;
    fd.shape = &amp;b2PolygonShape(m_polygon); // &lt;-- the problem
    return fd;
}
</code></pre>

<p>Although this doesn't produce any compile-time errors, I expect this will be a problem: <code>fd.shape</code> is a pointer. I'm casting my polygon object, to their polygon object, and then saving that location in memory. If I'm not mistaken, this will become immediately invalid after that line finishes executing.</p>

<p>So what's a nice workaround for this? I could use the <code>new</code> operator, but my class shouldn't really be allocating memory for some other class to clean up. I could actually store the <code>b2PolygonShape</code> in my class, but then I essentially have two copies of the same data (my polgon object, and their polygon object); I could get rid of mine, but it's a lot easier to work with, which is why I created it in the first place. I could remove the entire function and make other classes responsible for doing the conversion themselves, but that wouldn't be consistent with my other wrappers, and it isn't a very nice solution. Is there any happy middle ground I'm overlooking?</p>

<p><hr /></p>

<p>Code now looks like this:</p>

<pre><code>Fixture::operator b2FixtureDef() const {
    b2FixtureDef fd;
    fd.density = m_density;
    fd.friction = m_friction;
    fd.isSensor = m_isSensor;
    fd.restitution = m_restitution;
    fd.shape = new b2PolygonShape(m_polygon);
    return fd;
}
</code></pre>

<p>And gets used like this:</p>

<pre><code>void Body::addFixture(const Fixture&amp; fixture) {
    m_fixtures.append(fixture);
    b2FixtureDef fd = fixture;
    m_body-&gt;CreateFixture(&amp;fd);
    delete fd.shape;
}
</code></pre>

<p>My goal was that I could just go <code>m_body-&gt;CreateFixture(&amp;fixture)</code> and it would cast <code>fixture</code> to a <code>b2FixtureDef</code> and free up the resources by itself... but it doesn't look like that's possible with this stupid pointer dangling around.</p>
