简体   繁体   English

Qt,动态分配内存

[英]Qt, Dynamic allocation of memory

I have a little question: I made a little program where every time the user click on a QPushButon a new object is created with his pointer, here is my code: 我有一个小问题:我编写了一个小程序,每次用户单击QPushButon时,都会使用其指针创建一个新对象,这是我的代码:

ajoute *az = new ajoute;
QVBoxLayout *layoutPrincipal = new QVBoxLayout;

the problem is that every object which have been created have the same name so if i want delete a object there probably will have a error ? 问题是每个已创建的对象都具有相同的名称,所以如果我要删除对象,则可能会有错误?

PS : sorry for my bad english, i'm french PS:对不起,我英语不好,我是法语

Your object is most probably on stack, so next instance will not "remember" about previous one. 您的对象很可能在堆栈上,因此下一个实例将不会“记住”上一个实例。 More code would be required to fine tune explanation. 需要更多代码来完善说明。

Common solutions include : 常见的解决方案包括:

  • use an attribute (or many) in your class and delete before creating 在您的课程中使用一个(或多个)属性并在创建之前删除
  • use QSharedPointer and reset pointed data (thus actually freeing previous instance) 使用QSharedPointer并重置指向的数据(因此实际上释放了以前的实例)
  • (Qt way) make object children of a "parent QObject" : it will be cascade-deleted when root of the objet tree is disposed of. (Qt方式)使对象的子对象成为“父QObject”:当废弃对象树的根节点时,它将被级联删除。

The problem is that every object which have been created have the same name so if i want delete a object there probably will have a error? 问题是每个已创建的对象都具有相同的名称,因此如果我要删除对象,则可能会有错误?

It seems like you are creating a group of dynamically allocated objects and you don't know how to store their pointers. 好像您正在创建一组动态分配的对象,并且您不知道如何存储它们的指针。 The simplest way is to use a QVector<ajoute*> and store the dynamically allocated objects: 最简单的方法是使用QVector<ajoute*>并存储动态分配的对象:

QVector<ajoute*> v;

Now whenever you create an ajoute you just do: 现在,每当创建一个ajoute您都要做:

v.push_back( new ajoute );

That will add the pointer at the end of the vector (container). 这会将指针添加到向量(容器)的末尾。 Then you can access them in order by doing: 然后,您可以通过以下操作按顺序访问它们:

v[0]; // first
v[1]; // second
v[2]; // third

And obviously you can delete them as: 很明显,您可以将它们删除为:

delete v[0]; // example

Just remember to delete the pointer inside the vector as well: 只需记住还要删除向量中的指针:

v.remove(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM