简体   繁体   中英

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:

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

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)
  • (Qt way) make object children of a "parent QObject" : it will be cascade-deleted when root of the objet tree is disposed of.

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*> v;

Now whenever you create an ajoute you just do:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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