Size of a C++ array in 64 vs 32 bit environment
suppose I have a class defined as follows
class foo
{
char [10] bar;
}
How would the size of this class differ wh开发者_如何学JAVAen in a 64 bit environment compared to a 32 bit one, assuming no padding/packing.
I believe the 64 bit version of the class would be 4 more bytes in length since:
- The class must contain a char* in order to point to the start of the array bar
- an char* is 8 bytes in a 64 bit environment vs 4 bytes in a 32 bit environment
Am I correct?
Thanks!
A further question about how arrays actually work If there is no pointer stored when you declare an array, how come you can get an address out of the array name and do things like bar[0], bar[1], etc?
No you are not. char [] bar;
won't even compile, char bar[10];
is the correct syntax, and no, no pointer is stored, sizeof(char) is always 1 and sizeof bar will be 10, regardless of the architecture.
Now for your additional question: You must understand the notion of lvalues and rvalues and lvalue-to-rvalue conversions. Usually lvalue-to-rvalue conversions "do nothing". An excetion is that an lvalue-to-rvalue conversion for array of T is conversion to a pointer to T which points to the first element of the array.
Also a function declaration taking an array of T by value is equivalent to a function declaration taking a pointer to T.
sizeof(char) is defined as 1 in the C++ standard, no matter what your architecture is. Your struct is an array of 10 chars, not a pointer to an array.
Also, the proper declaration would be char bar[10]
.
You're probably thinking about char *bar
- now that would be a 4 bytes vs 8 bytes in 32-bit vs 64-bit.
The one way you might see a difference would be if the compiler decided to insert some padding after the array so if you were to create an array of these objects, each would be nicely aligned. For example, on a 32-bit target it might pad it out to 12 bytes, but on a 64-bit target to 16 bytes instead.
Without padding, however, the two would be the same size -- you're not defining a pointer, so the difference in pointer size has no effect here.
The example you give will not become larger on a 64-bit environment.
class foo
{
char bar[10];
};
However, it's also quite useless because it has no public members.
Many classes look more like this:
class foo2
{
public:
char bar[10];
virtual ~foo2() {}
};
A class with any virtual members at all, such as foo2 has, will grow when the pointer size grows. However, with most compilers, there is only one pointer regardless of how many virtual members.
Either way, it's only a concern for classes that you create a large number of (> say 20000 instances).
精彩评论