我的多态过程会导致内存泄漏吗?

时间:2019-05-30 03:46:25

标签: c++ c++11

我有一个TreeItem类,其中有一个名为Container的数据成员

class TreeItem
{
 public:    
 void setContainer(const Container &data);

 private:
    QList<TreeItem*> childItems;
    Container itemData;
     TreeItem* parentItem;
 };

setContainer的定义

void TreeItem::setContainer(const Container &cont)
 {
   itemData = cont; 
 }

容器类的定义

class Container
 {
  private:
  std::string stdstrContainerName;
  std::string stdstrPluginType;
  Geometry* Geom;

public:
 Container();
 Container(std::string, std::string, Geometry* geometry );
 Container(const  Container& obj);
};

Container::Container( std::string strName, std::string strType,  
Geometry* geometry) : Geom(geometry)
{   
  stdstrContainerName = strName;
  stdstrPluginType = strType;
  qDebug() << geometry->isValid();
}

我使用我的TreeModel类在TreeItem对象中设置Container的值

void  TreeModel::SetContainer(const QModelIndex &index,  Container* Cont)
 {
   TreeItem *item = getItem(index);
   item->setContainer(*Cont);

  }

Geometry类的数据类型Container具有一个名为draw的虚函数

Class Geometry
{
 public:    
     std::string stdstrType;
     bool bValid;

 public:
// Other Functions
 virtual void draw();

};


还有其他类是从Geometry类派生的

 class Sph : public Geometry
  {
   public:
   Sph( float radius , float segments );
  ~Sph();
  void init();
  void CleanUp();
  void draw();

 private:
   float fRadius, fSegments;
   bool isInited;
   unsigned int m_VAO, m_VBO;
   int iNumsToDraw;
   SumShader shader;
   bool isChanged;
};

这是我用来将Container设置为TreeItem类的过程。

 void WavefrontRenderer::AddSphere()
  {
    QModelIndex index = treeView->selectionModel()->currentIndex();
    QAbstractItemModel *model = treeView->model();
    TreeModel *myModel = qobject_cast<TreeModel*>(model);

    Sph* sphere = new Sph( 0.1 , 32);
   sphere->setValidState(true);
   sphere->stdstrType = "Sphere";
   if (!model->insertRow(index.row() + 1, index.parent()))
      return;

   Container cont("Sphere" , "SPHERE" , sphere );
   QModelIndex child = model->index(index.row() + 1, 0, index.parent());
   model->setData(child, QVariant("Container"), Qt::EditRole);
   myModel->SetContainer(child, &cont);
   delete sphere // This line gives error

}


一切正常,但我有几个问题。

1)因为我正在创建一个新的对象Sph* sphere = new Sph( 0.1 , 32);但不删除它会导致内存泄漏吗?

2)在TreeItem上设置它后,尝试删除它时,出现了内存错误

0 个答案:

没有答案