堆/栈上的类成员分配?
如果一个类声明如下:
class MyClass
{
char * MyMember;
MyClass()
{
MyMember = new char[250];
}
~MyClass()
{
delete[] MyMember;
}
};
并且可以这样做:
class MyClass
{
char MyMember[250];
};
如何在堆上分配类,就像我这样做 MyClass * Mine = new MyClass();
分配的内存是否也与类实例化一起分配第二个示例中的 250 字节?该成员在 MyClass 对象的整个生命周期内都有效吗? 对于第一个例子,在堆上分配类成员是否实用?
If a class is declared as follows:
class MyClass
{
char * MyMember;
MyClass()
{
MyMember = new char[250];
}
~MyClass()
{
delete[] MyMember;
}
};
And it could be done like this:
class MyClass
{
char MyMember[250];
};
How does a class gets allocated on heap, like if i do MyClass * Mine = new MyClass();
Does the allocated memory also allocates the 250 bytes in the second example along with the class instantiation? And will the member be valid for the whole lifetime of MyClass object?
As for the first example, is it practical to allocate class members on heap?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,是的,是的。
不过,您的第一个示例有一点错误:因为它的数据成员之一是带有堆分配数据的指针,所以它还应该声明一个复制构造函数和赋值运算符,例如 . ..
Yes, yes, and yes.
Your first example has a bit of a bug in it, though: which is that because it one of its data members is a pointer with heap-allocated data, then it should also declare a copy-constructor and assignment operator, for example like ...
早期注意事项:使用
std::string
而不是堆分配的 char[]。它将在构造函数中进行堆分配,与在堆栈中分配 MyClass 的方式相同。这取决于你所说的“连同”是什么意思,它不一定会被分配在一起。
是的。
是的,在某些情况下。有时您希望最小化头文件中的包含内容,有时您将使用工厂函数来创建成员。但通常情况下,我只使用一个简单的非指针成员。
Early note: use
std::string
instead of a heap allocated char[].It will be heaped allocated in the constructor, the same way as in a stack allocated MyClass. It depends what you mean by "along with", it won't necessarily be allocated together.
Yes.
Yes, in certain cases. Sometimes you want to minimize the includes from the header file, and sometimes you'll be using a factory function to create the member. Usually though, I just go with a simple non-pointer member.
当您调用 new 时,它会从堆中分配,否则它会从堆栈中分配(我们将忽略 malloc 及其同类)。
在第一个示例中,将在两者中分配空间:堆栈上的 4 个字节用于 MyClass 的实例(假设为 32 位指针),堆上的 250 个字节用于分配给 MyMember 的缓冲区。
在第二个示例中,将在堆栈上为 MyClass 实例分配 250 个字节。在这种情况下,MyMember 被视为实例的偏移量。
When you call
new
it allocates from the heap, otherwise it allocates from the stack (we'll ignoremalloc
and its ilk).In your first example, there will be space allocated in both: 4 bytes on the stack for the instance of MyClass (assuming 32-bit pointers), and 250 bytes on the heap for the buffer assigned to MyMember.
In the second example, there will be 250 bytes allocated on the stack for the instance of MyClass. In this case, MyMember is treated as an offset into the instance.