"new"创建的实例的所有成员变量是否都存在于堆上而不是堆栈上?

Do all member variables of a "new" created instance exist on the heap rather than the stack?

本文关键字:于堆 堆栈 存在 是否 实例 创建 new 变量 成员      更新时间:2023-10-16

标题并没有真正做到这个正义......

因此,如果我使用 new 创建一个类(在本例中为 Course,如在高尔夫球场中(,因此它是在堆上创建的,并且 Course 包含另一个类 Holes 的向量,该向量是否必须是 Hole* 的向量才能将它们放在堆上?

class course {
public:
course(std::string file);
private:
std::string name;
std::vector<hole> holes;
};
class hole {
public:
hole(std::string data);
private:
std::vector<vec3> vertices;
std::vector<int> triIndex;
std::vector<int> boundaryIndex;
};
course currentCourse = new course("datafile.dat");

我的假设是,当然在堆上,那么所有成员当然也会在堆上,但我现在怀疑自己,是的,这是作业的一部分,我确实必须考虑内存管理 - 我以前从未遇到过这种情况,我甚至不确定如何测试变量是在堆栈内存中还是堆内存中。

我真的希望我已经把这个问题说清楚了,因为我在措辞上遇到了麻烦,因此搜索没有多大帮助:(如果人们能为我指出正确的方向,我非常乐意发布更新。

量必须是孔* 的向量吗?

不。std::vector是一个使用动态(堆(内存的容器(std::string也是如此(。如果您使用了在堆栈上分配的容器,答案仍然是否定的,因为您的假设

当然在堆

上,那么所有成员当然也会在堆上

是正确的。

在您的情况下,不需要new。您可以简单地:

course myCourse("datafile.dat")

一个小总结:

struct S
{
void f() { int a = 0; /* local variable a is always on the stack */ }
int _i = 1; // stack or heap depending on whether the instance of S
// is on the stack or on the heap
std::vector<int> _v; // always uses heap (small std::vector's could store their contents
// on the stack, but I'll consider that out of scope)
};

请注意,如果S的实例位于堆栈上,则成员_v位于堆栈上。但是,存储在_v中的内容位于堆上。