2

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:

  1. THuman male; in which the object is created and then goes out of scope when the block {... code ...} ends

  2. THuman* male = new THuman I can control the object's life and destroy it with a delete


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++).

Raffaele Rossi
  • 2,737
  • 2
  • 20
  • 49
  • https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization –  Dec 24 '16 at 19:56
  • 1
    Possible duplicate of [What is the lifecycle of a C++ object?](http://stackoverflow.com/questions/17121305/what-is-the-lifecycle-of-a-c-object) – Borgleader Dec 24 '16 at 19:57
  • 1
    Avoid using pointers and dynamic allocation as much as you can. They will only lead to problems and weird behavior if you do not understand them very well. Automatic storage (local variables on "the stack") is safe and works well as long as you only need the variable within the current (or nested) blocks. In modern C++ there's seldom a need for pointers at all, except for polymorphism. – Some programmer dude Dec 24 '16 at 19:57
  • No you don't want to control lifetime manually. That isn't robust against exceptions. C++ has no finally. You need not to write delphi code with c++ syntax. Program into the language. – David Heffernan Dec 24 '16 at 20:21
  • @Someprogrammerdude No non trivial program can be written without pointers! – curiousguy Jan 26 '17 at 01:41

3 Answers3

3

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:

  • Each new must be matched with one an only one delete
  • each new[] (creation of dynamic arrays) must be matched with one an only one delete[]

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).

A.S.H
  • 28,433
  • 5
  • 19
  • 45
  • So in C++ it's preferred to avoid pointers in general? Since pointers are more "C style" – Raffaele Rossi Dec 24 '16 at 20:21
  • @RaffaeleRossi This is opinion based, some will tell you so, others (like me) will tell you feel free to use pointers as they are a very powerful idiom. Others will promote the use of smart pointers, but that IMO is a different concern. – A.S.H Dec 24 '16 at 20:25
  • So I can say that it is like having a mountain bike or a city bike? Both does the same but people prefer one or the other, according also with the use they need – Raffaele Rossi Dec 24 '16 at 20:27
  • @RaffaeleRossi Actually, no it is not a matter of preference. If the object is needed only "locally", dont `new it`. If it is created at some function and need to be handed to another, so it needs to survive the scope of its creation, you new-it and return a pointer. – A.S.H Dec 24 '16 at 20:30
  • "_So in C++ it's preferred to avoid pointers in general?_" There is no way to write non trivial C++ without using pointers! – curiousguy Jan 26 '17 at 01:41
2

Is it correct if I say that method 1 allocates memory on the stack and method 2 on the heap?

  • Yes

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?

  • Consider using smartpointers instead of raw pointers. Smartpointers are objects which handle pointer resources and make them more safe to use. However, if you cannot use smart pointers, make sure to call delete on the pointer to release the previous allocated memory from the heap before you assign NULL to it. Otherwise you will have leaked resources. To check your program memory management you can run valgrind
Community
  • 1
  • 1
SebNag
  • 903
  • 9
  • 27
  • When you say "yes", for method 1 you should be clear that some storage will be allocated on the stack, and then the object's constructor may allocate more on the heap. –  Dec 24 '16 at 20:01
  • 1
    Also note that the C++ specification doesn't specifically say that local variables are stored on "the stack". It's the most common method of handling local variables, but the C++ specification only say that they have "automatic" storage. A compiler may choose to store local variables differently. – Some programmer dude Dec 24 '16 at 20:07
2

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?

if you do this before calling delete you leaked memory and if you call delete on a NULL pointer you get a seg fault(application crash).

the best way is to use stack objects, but if you need to manage object's existence use smart pointer(unique_ptr, shared_ptr) as suggested above.

Note : by "Leaked memory" I mean that this region is lost it cannot be accessed from program , nor freed by OS.

chedy najjar
  • 591
  • 5
  • 19