neb*_*rot 7 c++ heap stack memory-management
来自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
}
Run Code Online (Sandbox Code Playgroud)
但是这样的事情怎么样?
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?
}
Run Code Online (Sandbox Code Playgroud)
说我foo
在里面添加了一个全局数组method3()
.如果我foo
在方法退出后尝试访问其中一个数据成员,那会有用吗?并且method3()
容易出现内存泄漏?
提前致谢.
Foo foo();
Run Code Online (Sandbox Code Playgroud)
通过foo
返回Foo
对象的名称声明一个函数,并且不接受任何参数.它被称为C++中最令人烦恼的解析.你可能意味着:
Foo foo;
Run Code Online (Sandbox Code Playgroud)
它创建一个foo
对象本地/自动存储.一旦{ }
声明它的作用域结束,该对象就会自动释放.
Foo *foo = new Foo(); // allocates foo on the heap
delete foo;
Run Code Online (Sandbox Code Playgroud)
这是真的,foo
一旦你调用,freestore指向的对象就会被释放delete
.没有内存泄漏.
Foo foo = *new Foo();
Run Code Online (Sandbox Code Playgroud)
Foo
在freestore上分配对象,然后使用该对象的副本进行初始化foo
.由于您没有指向freestore分配对象的指针,因此会导致内存泄漏.请注意,如果析构函数Foo
具有一些导致副作用的代码,那么它不仅仅是内存泄漏,而是未定义的行为.