这里有两个问题。首先,如果我需要在b2BlockAllocator
之前创建Clone
,然后在克隆后删除(哪里?)? Xcode分析工具未显示C++泄漏...
b2FixtureDef fixd = fix->fixture;
const b2Shape *shape = fixd.shape;
if(shape->GetType()== b2Shape::e_polygon && flip)
{
b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(new b2BlockAllocator());
for(int i=0;i<ps->m_vertexCount;i++)
{
ps->m_vertices[i].x *= -1;
ps->m_vertices[i].y *= -1;
}
ps->Set(&ps->m_vertices[0], ps->m_vertexCount);
body->CreateFixture(ps, 1.0f);
...
在这段代码中,我将缓存的形状对象,克隆它,修改顶点,设置为计算法线并将其分配给主体。问题-这合法吗?
更新:
-(void) addFixturesToBody:(b2Body*)body forShapeName:(NSString*)shapeName flip:(BOOL)flip
{
BodyDef *so = [shapeObjects_ objectForKey:shapeName];
assert(so);
FixtureDef *fix = so->fixtures;
while(fix)
{
b2FixtureDef fixd = fix->fixture;
const b2Shape *shape = fixd.shape;
if(shape->GetType()== b2Shape::e_polygon && flip)
{
b2BlockAllocator allocator;
b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&allocator);
for(int i=0;i<ps->m_vertexCount;i++)
{
ps->m_vertices[i].x *= -1;
ps->m_vertices[i].y *= -1;
}
ps->Set(&ps->m_vertices[0], ps->m_vertexCount);
body->CreateFixture(ps, 1.0f);
}
else
{
NSLog(@"noflip...%@", shapeName);
body->CreateFixture(&fix->fixture);
}
fix = fix->next;
}
}
最佳答案
我试图找到类似答案时晚了4年才回复。似乎很少有人在Box2D方面付出更多的努力。
因此,您肯定在泄漏,因为new b2BlockAllocator
不会在任何地方被您或克隆函数删除。
只需创建一个本地b2BlockAllocator,以便在超出范围时将其销毁。就是这样。
b2BlockAllocator cloneHelper;
b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&cloneHelper);