I come from many years of development in Java, and now that I want switch to C++ I have hard times understanding the memory management system.
Let me explain the situation with a small example:
From my understanding, you can allocate space either on the stack or on the heap. The first is done by declaring a variable like this:
int a[5]
or
int size = 10;
int a[size]
On the contrary, if you want to allocate memory on the heap, then you can do it using the "new" command. For example like:
int *a = new int[10]; (notice that I haven't tried all the code, so the syntax might be wrong)
One difference between the two is that if it is allocated on the stack when the function is finished then the space is automatically deallocated, while on the other case we must explicitly deallocate it with delete().
Now, suppose I have a class like this:
class A {
const int *elements[10];
public void method(const int** elements) {
int subarray[10];
//do something
elements[0] = subarray;
}
}
Now, I have few questions:
- in this case, subarray is allocated on the stack. Why after the function method has finished, if I look on elements[0] I still see the data of subarray? Has the compiler translated the first allocation in a heap allocation (and in this case, is this a good practice)?
- if I declare subarray as "const", then the compiler does not let me assign it to elements. Why not? I thought that the const only concerns the inability to change the pointer, but nothing else.
- (this is probably quite stupid) suppose I want to allocate "elements" not with a fixed 10 elements, but with a parameter that comes from the constructor. Is it still possible to allocate it in the stack, or the constructor will always allocate it in the heap?
Sorry for such questions (that might look silly to a expert C programmer), but the memory management system of C++ is VERY different from Java, and I want to avoid leakings or slow code. Many thanks in advance!