gpt4 book ai didi

C++ 在堆和堆栈上分配内存?

转载 作者:可可西里 更新时间:2023-11-01 18:29:34 24 4
gpt4 key购买 nike

我有 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() 是否容易发生内存泄漏?

提前致谢。

最佳答案

Foo foo(); 

通过名称 foo 声明一个函数,它返回一个 Foo 对象并且不接受任何参数。它被称为 C++ 中最令人烦恼的解析。你的意思可能是:

Foo foo; 

它在本地/自动存储中创建一个foo 对象。一旦声明它的范围 { } 结束,该对象就会自动释放。


Foo *foo = new Foo();   // allocates foo on the heap
delete foo;

这是真的,一旦您调用 deletefoo 指向的 freestore 上的对象就会被释放。没有内存泄漏。


 Foo foo = *new Foo(); 

在 freestore 上分配一个 Foo 对象,然后使用该对象的拷贝来初始化 foo。由于您没有指向自由存储分配对象的指针,因此会导致内存泄漏。请注意,如果 Foo 的析构函数包含一些导致副作用的代码,那么它不仅仅是内存泄漏,而是未定义的行为。

关于C++ 在堆和堆栈上分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15049509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com