Provenendo da uno sfondo Java, sono ancora un po 'confuso sull'allocazione della memoria in C++. Sono abbastanza sicuro che le prime due affermazioni siano corrette:C++ Allocazione della memoria sull'heap e stack?
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
}
Ma che dire di qualcosa del genere?
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 Ho aggiunto foo
ad una matrice globale all'interno method3()
. Se provassi ad accedere a uno dei membri dei dati di foo
dopo l'uscita dal metodo, funzionerebbe? Ed è method3()
incline a perdite di memoria?
Grazie in anticipo.
'Foo pippo();' in realtà non assegna nulla. Dichiara una funzione. – chris