这里有两个问题。首先,如果我需要在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;
}
}
答案 0 :(得分:0)
我不会使用Box2D分配器,因为我不会使用b2Shape::Clone
方法。不是直接的。相反,我会做以下事情:
b2PolygonShape
,Set
上调用b2PolygonShape
,为其分配修改过的顶点,b2PolygonShape
方法,使用原始正文中指定的b2Body::CreateFixture
创建新的装置,b2Body::DestroyFixture
方法来摆脱原来的夹具。 b2BlockAllocator
类可以被实例化并用于动态分配内存,而内存又可以在b2BlockAllocator
实例的生命周期内使用,但是这样做的开销超过了你正试图这样做。
答案 1 :(得分:0)
我试图找到一个类似的答案,我迟了4年回复。似乎很少有人用Box2D加倍努力。
所以,你肯定是在泄漏,因为new b2BlockAllocator
不会被你或克隆功能删除。
只需创建一个本地b2BlockAllocator,以便在超出范围时将其销毁。就是这样。
b2BlockAllocator cloneHelper;
b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&cloneHelper);