gpt4 book ai didi

c++ - 关于内存管理、栈、堆的问题

转载 作者:行者123 更新时间:2023-11-30 01:28:22 28 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Does this type of memory get allocated on the heap or the stack?

我有几个与内存相关的问题,希望你们能够回答。考虑这段代码,其中 Foo 代表一个具有大量方法和大量原始数据成员的大类:

class Foo {
public:
Foo() : // Initialize all data members ...
{ }

// Lots of methods ...

~Foo() { /*Nothing needed here ... correct?*/ }

private:
int a;
int b;
char c;
double d;
// Lots of other primitive data members (no pointers) ...
};

class Bar {
public:
void func() {
foo = new Foo();
}

// Assuming Bar::func() is always called before deletion ...
~Bar() { delete foo; }
private:

Foo* foo;
};

int main() {
Bar bar;
bar.func();

Bar* barptr;
barptr->func();

return 0;
}

我的问题是,当我调用 bar.func() 时,Foo 的所有数据成员都分配在 stack 内存上还是在 内存上(我知道foo 会在堆上……我想!)?当我调用 barptr->func() 时会怎样?例如,Foo::a 是在堆栈上还是在堆上?

此外,我是否需要显式删除 Foo::~Foo() 中的任何内容? Foo 只有原始本地数据成员,并且没有任何函数使用 newmalloc()

在我完全不知道我在说什么的情况下,如果有人能解释这些数据的存储位置,我将不胜感激。

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