这里有两个问题。首先,如果我需要在 Clone
之前创建 b2BlockAllocator
然后在克隆之后删除(在哪里?)? 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);
...
在这段代码中,我获取缓存的形状对象,克隆它,修改顶点,设置计算法线并将它的对象分配给 body 。问题 - 这合法吗?
更新:
-(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
不会在任何地方被删除,无论是您还是 Clone 函数。
只需创建一个本地 b2BlockAllocator,以便在超出范围时将其销毁。就是这样。
b2BlockAllocator cloneHelper;
b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&cloneHelper);
关于c++ - 如何使用 Box2D 分配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501980/