try to learn C++ and programming in general. Currently I am studying open source
ID: 658574 • Letter: T
Question
try to learn C++ and programming in general. Currently I am studying open source with help of UML. Learning is my hobby and great one too.
My understanding of memory allocation in C++ is that it should be symmetrical. A class is responsible for its resources. If memory is allocated using new it should be returned using delete in the same class. It is like in a library you, the class, are responsibility for the books you have borrowed and you return them then you are done.
This, in my mind, makes sense. It makes memory management more manageable so to speak.
So far so good. The problem is that this is not how it works in the real world.
In Qt for instance, you create QtObjects with new and then hand over the ownership of the object to Qt. In other words you create QtObjects and Qt destroys them for you. Thus unsymmetrical memory management. Obviously the people behind Qt must have a good reason for doing this. It must be beneficial in some kind of way,
My questions is:
What is the problem with Bjarne Stroustrups idea about a symmetrical memory management contained within a class?
What do you gain by splitting new and delete so you create an object and destroy it in different classes like you do in Qt.
Is it common to split new and delete and why in such case, in other projects not involving Qt?
Thanks for any help shedding light on this mystery!
Explanation / Answer
In modern C++ you typically want to use the Resource Acquisition Is Initialization (RAII) idiom. The idea is that any resource that you allocate should be wrapped into a class, and it should be deleted/closed/cleaned up by the class's destructor. A resource is anything that you need to de-allocate, close, or otherwise clean up when you are done with it. Most often a resource is memory, but it could be other things like files or network connections.
In some cases the wrapping class can be complex, representing some piece of program logic. In most cases the wrapping class can be very simple, existing solely for the purpose of de-allocating the resource at the right time in the right way. An example of that is a smart pointer.
I haven't looked at Qt in a very long time. However, letting the user allocate an object, and pass a raw pointer into a library function that later de-allocates it is a rather outdated pattern. If the Qt function throws an exception before it has a chance to delete your object, you will inevitably have a memory leak. The object should be wrapped into a smart pointer, whose destructor will delete it automagically, including the case when an exception is thrown.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.