Pochodzę z tła Java, wciąż jestem trochę zdezorientowany co do przydzielania pamięci w C++. Jestem pewien, że pierwsze dwa stwierdzenia są poprawne:C++ Przydzielanie pamięci na stercie i stosie?
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
}
Ale co z czymś takim?
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 dodaje foo
do globalnej tablicy wewnątrz method3()
. Jeśli próbowałem uzyskać dostęp do jednego z elementów danych foo
po zakończeniu metody, czy to zadziała? I czy jest method3()
podatna na przecieki pamięci?
Z góry dziękuję.
'Foo foo();' faktycznie nie przydziela niczego. Deklaruje funkcję. – chris