Qt Memory management mechanism

Source: Internet
Author: User

This article was first published on my homepage http://www.devbean.info, and will be published directly there. Now there is a Flex 4 and "from C + + to Objective-c" series, thank you for your support!

Strongly typed languages always explicitly or implicitly contain type information for objects when they are created. That is, a strongly typed language is always associated with the type of the object when it allocates the object memory space. In contrast, weakly typed languages do not do so. After allocating memory space, there are two ways to free up space: by hand, or by using the garbage collector. C + + requires developers to manually free up memory space. The advantage of this is that the developer has complete control of the interior and knows when the release is appropriate. Java uses the garbage collector. It will have a thread in the background to constantly see which objects are not being used and can be recycled based on certain algorithms. This frees the developer from the underlying implementation and focuses on the business logic.

This article focuses on QT memory management, which uses the QT mechanism to implement a simple garbage collector.

C + + memory management mechanism

C + + requires developers to manage their own memory. There are three types of strategies:

    1. Let the created object delete its own sub-object (the sub-object referred to here refers to the object's properties, not the subclass, similar to the following);
    2. Let the last object handle the delete;
    3. Regardless of memory.

The last one is usually a "memory leak" and is considered a bug. So now we are going to choose which of the previous two is more appropriate. Sometimes, delete creates an object that is much simpler than all its child objects, and sometimes finding the last object can be quite difficult.

Qt Memory management mechanism

Qt can maintain the hierarchy of objects internally. For visual elements, this hierarchy is the child component's relationship to the parent component, and for non-visual elements, it is the dependency of one object to another. In Qt, deleting a parent object deletes its child objects together. This helps reduce memory problems by 90%, creating a mechanism similar to garbage collection.

Qpointer

Qpointer is a template class. It is similar to a normal pointer, except that Qpointer can monitor dynamically allocated objects and update them when the object is deleted.

  1. Qpointer behaves like a normal pointer
  2. Qdate *mydate = new Qdate (Qdate::currentdate ());
  3. Qpointer mypointer = MyData;
  4. Mydate->year (); ///2005
  5. Mypointer->year (); ///2005
  6. Qpointer will behave differently when the object is delete
  7. Delete mydate;
  8. if (mydate = = NULL)
  9. printf ("clean pointer");
  10. Else
  11. printf ("dangling pointer");
  12. Output dangling pointer
  13. if (Mypointer.isnull ())
  14. printf ("clean pointer");
  15. Else
  16. printf ("dangling pointer");
  17. Output clean pointer

Note the above code. After a raw pointer delete, its value is not set to NULL, and therefore becomes a wild pointer. However, Qpionter does not have this problem.

Qobjectcleanuphandler

The Qt object Cleaner is an important part of implementing automatic garbage collection. It can register many sub-objects and automatically delete all child objects when they are deleted. At the same time, it can also identify if a child object has been deleted, thereby removing it from its list of child objects. This class can be used for cleanup of classes that are not in the same hierarchy, for example, when a button is pressed to close many windows, because the window's parent property is not likely to be set to a button in another window, this class can be quite handy when used.

  1. Create an instance
  2. Qobjectcleanuphandler *cleaner = new Qobjectcleanuphandler;
  3. Create window
  4. Qpushbutton *w = new Qpushbutton ("Remove Me");
  5. W->show ();
  6. Register the first button
  7. Cleaner->add (w);
  8. If the first button is clicked, delete itself
  9. Connect (w, SIGNAL (clicked ()), W, SLOT (Deletelater ()));
  10. Create a second button, note that this button does not have any action
  11. w = new Qpushbutton ("nothing");
  12. Cleaner->add (w);
  13. W->show ();
  14. Create a third button to delete all
  15. w = new Qpushbutton ("Remove All");
  16. Cleaner->add (w);
  17. Connect (w, SIGNAL (clicked ()), cleaner, SLOT (Deletelater ()));
  18. W->show ();

In the code above, three windows with only one button are created. When the first button is clicked, it will delete itself (through the Deletelater () slot), at which point the cleaner automatically clears it from its own list. When the third button is clicked, The Cleaner is deleted, which removes all windows that are not closed at the same time.

Qt Garbage Collection

As objects become more complex, it is difficult to decide when to make a delete operation when this object is used in many places. Fortunately, Qt has a good garbage collection mechanism for all classes that inherit from Qobject. There are many ways to implement garbage collection, the simplest is the reference count, and the other is to save all objects. We will explain these two implementations in detail below.

Reference count

The application count is the simplest garbage collection implementation: Each object is created, the counter is incremented by 1, minus 1 for each deletion.

  1. Class Countedobject
  2. {
  3. Public
  4. Countedobject ()
  5. {
  6. ctr=0;
  7. }
  8. void Attach ()
  9. {
  10. ctr++;
  11. }
  12. void Detach ()
  13. {
  14. ctr--;
  15. if (Ctr <= 0)
  16. Delete this ;
  17. }
  18. Private
  19. Int Ctr;
  20. };

Each child object should call the Attach () function after it is created, and the counter will be incremented by 1, and the detach () update counter should be called when it is deleted. However, this class is primitive and does not use Qt's convenient mechanism. Below we give a Qt version of the implementation:

  1. Class Countedobject: Public qobject
  2. {
  3. Q_object
  4. Public
  5. Countedobject ()
  6. {
  7. ctr=0;
  8. }
  9. void Attach (Qobject *obj)
  10. {
  11. ctr++;
  12. Connect (obj, SIGNAL (destroyed (qobject*)), SLOT (Detach ()));
  13. }
  14. Public Slots:
  15. void Detach ()
  16. {
  17. ctr--;
  18. if (Ctr <= 0)
  19. Delete this ;
  20. }
  21. Private
  22. Int Ctr;
  23. };

We use Qt's signal slot mechanism to automatically reduce the value of the counter when the object is destroyed. However, our implementation does not prevent the object from being created by calling two times attach ().

Record owner

A more appropriate implementation is not only to remember that several objects hold references, but also to remember which objects are. For example:

  1. Class Countedobject: Public qobject
  2. {
  3. Public
  4. Countedobject ()
  5. {
  6. }
  7. void Attach (Qobject *obj)
  8. {
  9. //Check owner
  10. if (obj = = 0)
  11. return;
  12. //Check whether you have added
  13. if (owners.contains (obj))
  14. return;
  15. //Registration
  16. Owners.append (obj);
  17. Connect (obj, SIGNAL (destroyed (qobject*)), SLOT (Detach (qobject*)));
  18. }
  19. Public Slots:
  20. void Detach (Qobject *obj)
  21. {
  22. //Delete
  23. Owners.removeall (obj);
  24. //If the last object is also deleted, delete itself
  25. if (owners.size () = = 0)
  26. Delete this ;
  27. }
  28. Private
  29. Qlist owners;
  30. };

Now our implementation has been able to prevent one object from calling Attach () and detach () multiple times. However, another problem is that we cannot guarantee that the object will call the Attach () function for registration. After all, this is not a C + + built-in mechanism. One solution is to redefine the new operator (this implementation is also complex, but avoids the case where an object does not call attach () registration).

This article is from Devbean ' s world:http://www.devbean.info.
Please indicate the original source of the article when reprinted: Http://www.devbean.info/2011/03/qt_memory_management/.
http://devbean.blog.51cto.com/448512/526734

Qt Memory management mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.