作为来自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?
}
如果我在
method3()
中将foo
添加到全局数组中,那么如果我在方法退出后尝试访问foo
的其中一个数据成员,是否有效?method3()
是否容易发生内存泄漏?提前感谢。
Foo foo();
实际上并不分配任何东西,它只是声明了一个函数。 - chris