来自 Java 背景,我对在 C++ 中分配内存仍然有些困惑。我很确定前两个陈述是正确的:
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
}
但是这样的事情呢?
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?
}
假设我添加foo到一个全局数组里面method3()。如果我在方法退出后尝试访问其中一个foo数据成员,那会起作用吗?并且method3()容易出现内存泄漏?
提前致谢。