Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Should I delete "new" object in a local function ?
QtWS25 Last Chance

Should I delete "new" object in a local function ?

Scheduled Pinned Locked Moved Solved General and Desktop
7 Posts 4 Posters 6.0k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    Hiloshi
    wrote on 15 Jun 2017, 15:37 last edited by
    #1

    Dear Sirs,

    I have a code as below:

    void MainWindow::on_pushButton_2_clicked()
    {
        QString *k = new QString;
    
        *k="H";
        delete k;      //Should I always do this ?
    }
    

    Should I always delete k before I leave the function?

    Thanks everyone.

    M 1 Reply Last reply 15 Jun 2017, 15:49
    0
    • H Hiloshi
      15 Jun 2017, 15:37

      Dear Sirs,

      I have a code as below:

      void MainWindow::on_pushButton_2_clicked()
      {
          QString *k = new QString;
      
          *k="H";
          delete k;      //Should I always do this ?
      }
      

      Should I always delete k before I leave the function?

      Thanks everyone.

      M Offline
      M Offline
      mrjj
      Lifetime Qt Champion
      wrote on 15 Jun 2017, 15:49 last edited by
      #2

      @Hiloshi
      Yes as k is not owned by anyone.

      However, why use new at all ?
      it will work just fine as

      QString k;

      1 Reply Last reply
      4
      • C Offline
        C Offline
        corruptedsyntax
        wrote on 15 Jun 2017, 15:59 last edited by corruptedsyntax
        #3

        Yes, memory should always be collected when finished with it, especially if the object using it is no longer referenceable. For your example there should be no problem simply allocating a QString object type on the Stack, which is always preferable to Heap allocation when possible (for performance reasons and to prevent programmers from making mistakes causing memory leaks). That said, when Heap allocation is necessary I would avoid using raw pointers & delete directly if at all possible.

        A good rule of thumb is that if you're allocating on the Heap then it's best practice to pass your pointer to another object which will handle variable lifetime and cleanup for you. For simple data allocated strictly in a local context I would advise a smart pointer type. For your example specifically, I would consider using the QScopedPointer type, though in my personal opinion there are few times where QScopedPointer is truly useful given that it already implies the lifetime of your variable is fixed to a local scope and that it should therefore likely be placed on the Stack (one exception being locally allocated arrays with sizes known only at runtime).

        Example use of QScopedPointer:

        void MainWindow::on_pushButton_2_clicked()
        {
            QScopedPointer<QString> k(new QString);
            *k="H";
            ...
        }//scope closes, QScopedPointer runs destructor and invokes delete upon held ptr
        
        1 Reply Last reply
        5
        • H Offline
          H Offline
          Hiloshi
          wrote on 16 Jun 2017, 01:23 last edited by
          #4

          Dear @mrjj , @corruptedsyntax ,

          Thanks for the help. For the QString example I provided is only for everyone easy understand.

          I have another question, in my example, if I run "pushButton_2" twice without delete k,
          will it occupy two physical memory ?

          C 1 Reply Last reply 16 Jun 2017, 12:58
          0
          • H Hiloshi
            16 Jun 2017, 01:23

            Dear @mrjj , @corruptedsyntax ,

            Thanks for the help. For the QString example I provided is only for everyone easy understand.

            I have another question, in my example, if I run "pushButton_2" twice without delete k,
            will it occupy two physical memory ?

            C Offline
            C Offline
            corruptedsyntax
            wrote on 16 Jun 2017, 12:58 last edited by corruptedsyntax
            #5

            @Hiloshi said in Should I delete "new" object in a local function ?:

            example, if I run "p

            If you run twice and never delete then the following will happen:

            1.)  Enter function on_pushButton_2_clicked()
            2.)  QString is created on Heap
            3.)  k is set to QString's address
            4.)  QString pointed to by k is assigned new string value
            5.) a.)  exit function on_pushButton_2_clicked()
                b.)  pointer k on Stack is deallocated, but QString value it points to on Heap is NOT deallocated
                c.)  QString on heap persist existence, however there is no way in code to reference it or even
                     know that it exist since we have lost the pointer to it
            6.)  At some future point, re-enter function on_pushButton_2_clicked()
            7.)  Create new QString on Heap (at this point there are 2 on Heap but 1 is not referenceable)
            continue...
            

            In short, the way the function is written (if you remove delete) you will create a new QString item everytime you enter the function and they will never be collected. If your program runs the function 500 times then there will be 500 unreachable strings remaining on the Heap.

            This can be a major problem if your program is intended to run indefinitely or run this function many times. In the past on 32-bit systems you might worry about running out of addressable space since 4GB of RAM was your limit. That's unlikely a real concern on modern 64-bit systems, but you will start seeing major performance drops as you continue making unneeded kernel calls for allocation and waste away all physical memory resources your system has, and don't get me started on how bad it'll be if these are all objects you unintentionally continue to render to a display.

            1 Reply Last reply
            3
            • H Offline
              H Offline
              Hiloshi
              wrote on 17 Jun 2017, 12:58 last edited by
              #6

              Dear @corruptedsyntax ,

              Thank you very much. Now I can understand.

              Thanks.

              1 Reply Last reply
              0
              • E Offline
                E Offline
                Eddy
                wrote on 17 Jun 2017, 15:26 last edited by
                #7

                Hi Hiloshi,

                There are very good Profiling and Memory Checking Tools that will detect memory leaks for you like Valgrind on Linux.
                When you use them you can experiment with different code approaches and see for yourself if there is something wrong with cleaning up your pointers.
                But if you have some concerns, don't hesitate to ask here on the forum. It's just a fun way of checking things yourself and learning by 'getting your hands dirty'.

                Happy coding,

                Eddy

                Qt Certified Specialist
                www.edalsolutions.be

                1 Reply Last reply
                2

                7/7

                17 Jun 2017, 15:26

                • Login

                • Login or register to search.
                7 out of 7
                • First post
                  7/7
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • Users
                • Groups
                • Search
                • Get Qt Extensions
                • Unsolved