+ 1

When to work with 'new' and 'delete'

How do I decide if I create objects on the stack or on the heap? Are there any guidelines, any rules of thumb?

7th Sep 2018, 10:52 PM
HonFu
HonFu - avatar
6 odpowiedzi
+ 1
HonFu few compiler allows this and few don't allow... better not to go with array if size is allocated dynamically... c++ expect that size must be known at compile time... that's the reason few compiler don't allow below also: int n = 10; int array[n]; reason is that size is variable and it can be changed... so , with above scenario also, you need to define const int n = 10. to conclude, array is not to be used for variable sizes.. use array pointer with new operator or else go with vector from STL
8th Sep 2018, 2:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
HonFu some thing you can decide at run time should be done using new and will get stored in heap
8th Sep 2018, 5:04 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Heap should be used in cases when the size of data isn't known at compilation time (for example the length of an array is given by argument).
8th Sep 2018, 5:52 AM
Sergey Ushakov
Sergey Ushakov - avatar
+ 1
Okay, that totally makes sense. One more piece in the right place, thanks! :)
8th Sep 2018, 3:02 PM
HonFu
HonFu - avatar
0
Ketan, Sergey, now I remember having read that you can not easily define an array 'pythonicly' by cin >> x; ar[x] or something like that (except with the heap stuff). I tried it on sololearn, it worked, I was like 'huh?' and forgot about it. So that doesn't work with a compiler, but can work on sololearn only because of the special pre-input situation here?
8th Sep 2018, 2:04 PM
HonFu
HonFu - avatar