I'm trying to translate some projects I've made with Delphi; an object can be declared in general as:
//I have the control of the object and I MUST delete it when it's not needed anymore
male := THuman.Create();
try
// code
finally
male.Free; (get rid of the object)
end;
Reading Stroustrup's book about C++ I have understood that (in short) his language doesn't need the finally
block because there are always workarounds. Now if I want to create a class I have two ways:
THuman male;
in which the object is created and then goes out of scope when the block{... code ...}
endsTHuman* male = new THuman
I can control the object's life and destroy it with adelete
The book suggests to use the first approach (even if both are fine) but I come from a Delphi background and I want to use the second method (I have the control of the object).
Questions. I cannot understand the difference between the 2 methods that C++ have for objects and reading online I got more confusion. Is it correct if I say that method 1 allocates memory on the stack and method 2 on the heap?
In method 2 (we're in the heap) if I assigned the value NULL
to the object, do I still have to call the delete?
For example Delphi allows to create instances only on the heap and the Free
deletes the object (like delete
in C++).
In Short
1- Objects not created with
new
have automatic lifetime (created in the stack as you say, but that is an implementation technique chosen by most compilers), they are automatically freed once they go out of scope.2- The lifetime of objects created with
new
(created in the heap, again as an implementation technique of most compilers), need to be managed by the programmer. Notice that deleting is NOT setting the pointer to NULL, it should happen before. The simple rule is:new
must be matched with one an only onedelete
new[]
(creation of dynamic arrays) must be matched with one an only onedelete[]
p.s: matched here concerns one-vs-one occurrence in the program's runtime, not necessarily in the code itself (you have control over when and where to delete any newed object).