How much memory is allocated to an object of this class?
In an object of this example class
class example
{
public:
int x;
}
an object would be allocated 4 bytes of memory. As an int would take 4 bytes.
How much memory would be allocated to an object of the following class -
class node
{
public:
int data;
node *prev, *next;
};
The int would take four bytes, but what about the 'next' and 'prev' pointers? What about the total size of an object of the class?
The total size of the object is sizeof(int) + 2*sizeof(node*) +
any padding the compiler might add between the members. Using sizeof(node)
is the only portable and reliable way to find that out.
Pointers are of size 4 bytes on x86 system or 8 bytes on x64 system.
So your total size of node
is 4 + 4 + 4 or 4 + 8 + 8 which is 12 bytes on x86 architecture, or 20 bytes on x64 architecture.
Because of padding however, on x64 architecture, the actual size of the class will be 24 bytes, because x64 architecture requires 8 byte alignment.
As mentioned by Oliver Charlesworth, you can also do std::cout << sizeof(node) << "n";
, which will tell you the exact size of class node
上一篇: 内存分配,指针指向无效
下一篇: 多少内存分配给这个类的对象?