Linked by Thom Holwerda on Mon 24th Aug 2009 15:06 UTC, submitted by diegocg
Qt Qt usually takes the boring memory allocation and deallocation from you, either through its implicitly shared containers, or with QObject's parent child relationship model. But every once in a while, we need to allocate something on the heap, and then the stress starts - where do we delete it, and how do we make sure to not leak the memory? To fix this problem, QScopedPointer was born. It will delete the object it is pointing to automatically when it goes out of scope.
Permalink for comment 380519
To read all comments associated with this story, please click here.
RE: its 2009
by ba1l on Tue 25th Aug 2009 13:38 UTC in reply to "its 2009"
ba1l
Member since:
2007-09-08

Because, at some point, someone has to care about memory management.

Qt generally handles memory management. A programmer writing a Qt application generally doesn't have to worry too much about it. Most objects do not need to be created with the new operator, so they are automatically destroyed when they go out of scope (end of function, or their containing object is destroyed). Most objects allocated on the heap have a clear owner - if you set the owner correctly, Qt will automatically destroy the object when it's owner is destroyed. Almost all of your memory management will be handled for you, either but C++ itself, or by Qt. There are some cases where it won't.

The article describes a smart pointer implementation that's been added to Qt. There are pretty common in modern C++ - essentially, they enforce ownership policies, and destroy the referenced object when appropriate. There are many types of smart pointers, each of which has slightly different behaviour. Using these, a programmer doesn't have to bother with the actual nuts and bolts of memory management - you just tell the compiler how to manage it, and let it handle everything for you.

Memory management can still cause problems in garbage collected languages like Java or .NET. That's why .NET has separate finalizers and the IDisposable interface, why C# has the using keyword, why they both have weak references, and so on. There are a multitude of ways to create memory leaks or resource leaks in a garbage collected languages, and it can often be very difficult to work out where the leaks are coming from.

Sure, you can write Java / .NET code while being completely ignorant of memory management. The garbage collector will save you from some problems (objects being destroyed while still referenced, and dealing with shared ownership), but it will not (and can not) prevent memory leaks, or excessive memory usage. You need to be just as careful writing a large Java / .NET application as you do writing a large C++ application.

Edited 2009-08-25 13:39 UTC

Reply Parent Bookmark Score: 5