"new"创建的实例的所有成员变量是否都存在于堆上而不是堆栈上?
Do all member variables of a "new" created instance exist on the heap rather than the stack?
标题并没有真正做到这个正义......
因此,如果我使用 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
中的内容位于堆上。
相关文章:
- 为什么堆栈和堆在内存中分离得如此之多?
- 为什么在堆栈和堆上创建变量会产生相同的程序集代码?
- C++类成员:堆栈与堆分配
- 在功能块中使用新运算符时存在于堆或堆栈上?
- "new"创建的实例的所有成员变量是否都存在于堆上而不是堆栈上?
- 巨大的内存分配:堆栈与堆
- C++17 和更新的 std::分配器是否适用于动态数量的自定义堆?
- 了解通过引用传递取消引用指针时C++堆/堆栈分配
- 在 C++ 中,映射相对于堆的优势是什么?
- C++堆/堆栈澄清
- 关于运行时/编译时和堆/堆栈的说明
- 更好地理解堆堆栈和列表
- OpenGL:将同形变换应用于矩阵堆栈
- C++-如何在程序退出时找到堆/堆栈损坏的源
- OOP 和堆/堆栈
- 是相对于对象是在堆栈上还是在堆上分配的继承成本
- 为什么范围基本循环不适用于堆中的数组,但适用于堆栈中的数组
- 内存管理-堆/堆栈的C++标准术语
- 堆/堆栈-进入QGraphicsItemGroup的变量的范围
- 删除std::lock_guard相对于其他堆栈分配对象的顺序/速度