在我的项目中,我制作了一个课程,如下所示,
class MyQt3D: public Qt3DExtras::Qt3DWindow
{
public:
MyQt3D()
{
// Root entity
m_rootEntity = new Qt3DCore::QEntity();
setRootEntity(m_rootEntity);
// Camera
Qt3DRender::QCamera* cameraEntity = camera();
cameraEntity->lens()->setPerspectiveProjection(45.0f, 16.0f/9.0f, 0.1f, 1000.0f);
cameraEntity->setPosition(QVector3D(0, 0, 40.0f));
cameraEntity->setUpVector(QVector3D(0, 1, 0));
cameraEntity->setViewCenter(QVector3D(0, 0, 0));
// For camera controls
Qt3DExtras::QOrbitCameraController *camController = new Qt3DExtras::QOrbitCameraController(m_rootEntity);
camController->setCamera(cameraEntity);
auto m_coneEntity = new Qt3DCore::QEntity(m_rootEntity);
// Cone shape data
Qt3DExtras::QConeMesh *cone = new Qt3DExtras::QConeMesh(m_coneEntity);
cone->setTopRadius(0.5);
cone->setBottomRadius(1);
cone->setLength(3);
cone->setRings(50);
cone->setSlices(20);
// ConeMesh Transform
Qt3DCore::QTransform *coneTransform = new Qt3DCore::QTransform(m_coneEntity);
coneTransform->setScale(1.5f);
coneTransform->setRotation(QQuaternion::fromAxisAndAngle(QVector3D(1.0f, 0.0f, 0.0f), 45.0f));
coneTransform->setTranslation(QVector3D(0.0f, 4.0f, -1.5));
Qt3DExtras::QPhongMaterial *coneMaterial = new Qt3DExtras::QPhongMaterial(m_coneEntity);
coneMaterial->setDiffuse(QColor(QRgb(0x928327)));
// Cone
m_coneEntity->addComponent(cone);
m_coneEntity->addComponent(coneMaterial);
m_coneEntity->addComponent(coneTransform);
}
~MyQt3D()
{
delete m_rootEntity;
}
protected:
Qt3DCore::QEntity *m_rootEntity;
};
由于我需要动态创建和销毁“ MyQt3D”类的对象,因此使用以下for循环来显示内存泄漏,
for(int i=0;i<20;i++)
{
MyQt3D* pView = new MyQt3D();
delete pView;
}
开始时,内存使用量为20 MB。 for循环后,内存使用量为80 MB。
可以在以下位置找到源代码项目文件: https://drive.google.com/drive/folders/1r8ZPaJVBOlYKywm7K-Se0J0ylQjbJILY?usp=sharing
如何解决内存泄漏问题? 谢谢。
答案 0 :(得分:0)
谢谢大家。在您的帮助下,解决了内存泄漏问题。
我使用来自Qt3D的示例代码“ BasicShape”进行了一些实验,该代码将显示一个窗口,如下所示, The running window of the project
我对该项目做了一些修改。也就是说,我添加以下代码,
for(int i=0;i<1000;i++)
{
Qt3DCore::QEntity *TempRootEntity = new Qt3DCore::QEntity();
SceneModifier *modifier = new SceneModifier(TempRootEntity);
delete modifier;
delete TempRootEntity;
qDebug()<<"delet!!!"<<i<< "\n";
}
之前
SceneModifier *modifier = new SceneModifier(rootEntity);
然后,运行此程序。即使我们执行了1000次循环,您仍然可以发现内存泄漏。关键是
delete TempRootEntity;
因为SceneModifier中的所有实体都是TempRootEntity的子代。 仅删除修饰符还不够!