Coming from a Java background, I'm still a little confused about allocating memory in C++. I'm pretty sure the first two statements are correct:
void method() {
Foo foo; // allocates foo on the stack, and the memory is freed
// when the method exits
}
void method2() {
Foo *foo = new Foo(); // allocates foo on the heap
delete foo; // frees the memory used by foo
}
But what about something like this?
void method3() {
Foo foo = *new Foo(); // allocates foo on the heap, and then copies it to the stack?
// when the method exits, the stack memory is freed, but the heap memory isn't?
}
Say I added foo
to a global array inside method3()
. If I tried to access one of foo
's data members after the method exits, would that work? And is method3()
prone to memory leaks?
Thanks in advance.