new command onto qobject ... doubt!

  • I use some number of New QObject ... macro ... the qobject live if my app live .... I read in these day some post and now I have a doubt .... I must use a Delete macro for every new or not? My app works fine ... so this request only serves to be sure to have a decent code at least.


  • Lifetime Qt Champion


    Can you show your code ?

  • Moderators

    @gfxx You should read this:
    Usually in C++ you have to free the memory you allocated via new keyword at some point to avoid memory leaks. You can use smart pointers to free the memory automatically.
    Many Qt classes (all classes derived from QObject) have "parent" parameter in their constructors. If you pass a parent to a child then child will be deleted when parent is deleted, so you do not have to delete child explicitly in this case:

    Parent *parent = new Parent();
    Child * child = new Child(parent);
    delete parent; // Here child will be deleted as well

  • @jsulm Thanks .... most of these in my code use smart pointer ..... but for shure 1 or 2 none ..... so I can simply convert it into smart pointer .... at these point my code is free of memory leaks (because it can be child of).

    I know the smart pointer usage ... anyhow I'm not expert enought so for shure I've place 1-2 new without delete .... than casually I read a post in these forum about memory leaks ... and I remember my error. But the code works so I asked.

    Thanks a lot.

Log in to reply