Dan Snow
Dan Snow

Reputation: 127

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 ?

P.S : sorry for my bad english, i'm french

Upvotes: 0

Views: 1711

Answers (2)

Shoe
Shoe

Reputation: 76240

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

Upvotes: 2

Bruce
Bruce

Reputation: 7132

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.

Upvotes: 2

Related Questions