+ 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?
6 Answers
+ 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
+ 2
HonFu some thing you can decide at run time should be done using new and will get stored in heap
+ 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).
+ 1
Okay, that totally makes sense.
One more piece in the right place, thanks! :)
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?