intx [] and X = new
what is the diffrence for between
int [10]
Answers
Answer:
The difference is that the first performs no allocation. It cannot be known if the entity ‘x’ exists in the stack, heap, or in the static data segment. All that can be known is that the pointer declaration did not allocate the entity ‘x’ and that for any sane use of raw pointers in modern C++ this should imply that it is not this pointer variable’s job to free the data pointed to (barring rare if-any exception). The second allocates a new integer to the heap however. Without cleanup, this will result in memory leak (or unintended object retention).
This is a very notable difference. Where for example this code:
void someFunc(int* ptr);
int foo() {
int x;
while (1) {
int* p = &x;
*p = 0;
someFunc(p);
if (*p) {
return *p
}
}
return 0;
}