Class members allocation on heap/stack?
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?
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 ...
MyClass(const MyClass& rhs)
{
MyMember = new char[250];
memcpy(MyMember, rhs.MyMember, 250);
}
Early note: use std::string
instead of a heap allocated char[].
Does the allocated memory also allocates the 250 bytes in the second example along with the class instantiation?
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.
And will the member be valid for the whole lifetime of MyClass object?
Yes.
As for the first example, is it practical to allocate class members on heap?
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.
When you call new
it allocates from the heap, otherwise it allocates from the stack (we'll ignore malloc
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.
链接地址: http://www.djcxy.com/p/14034.html上一篇: 宽度,布局
下一篇: 堆成员/栈上的类成员分配?