size of C++ class is 40 bytes instead of 36

My C++ class has data members of string and int. I thought its size is 36 bytes but the output says 40 bytes. Could someone explain?

#include <iostream>

using namespace std;

class SizeTest {

private:
    std::string name;
    int i;

};

int main(int argc, char** argv) {

    cout<<"sizeof(SizeTest) is : " << sizeof(SizeTest)<<endl;
}

Output:

sizeof(SizeTest) is : 40

Upvotes: 0

Views: 1029

Answers (2)

phuclv
phuclv

Reputation: 41764

First, std::string size isn't necessarily 32. For example it's 8-byte long on some 64-bit platforms and 24-byte on 64-bit libc++

On most implementations std::string contains a pointer to the char array, and 2 pointers or size_ts for the size and capacity. On a 64-bit platform those are 64-bit types so std::string must be aligned to 8 bytes, hence your class is also 8-byte aligned. Some implementations add another 8 dummy bytes to help align the data to 32-byte which is better than 8, and it's also better for small-string optimization since you can store more characters in a small string without resorting to allocate memory on heap

In your implementation std::string is a 32-byte type and int is a 4-byte type which makes the total size 36 bytes which isn't a multiple of 8. As a result 4 bytes of padding must be added to round the size to the next multiple of 8 so that when putting in an array all the instances of the class are properly aligned. The result is a 40-byte class

See also Why isn't sizeof for a struct equal to the sum of sizeof of each member?

You can pack the struct in some compilers using __attribute__ ((__packed__)) or #pragma pack to make the size 36-byte but it's a really really bad idea to do. Anyway you can see the demo on Godbolt

Upvotes: 3

eerorika
eerorika

Reputation: 238311

Could someone explain?

sizeof always returns the correct size. Thus, we can deduce that your expectation of the size was wrong.

You didn't explain why you thought what you did, but most likely cause for the mistake is failing to take memory alignment into consideration.

I thought, string is 32 bytes

It can be on some systems. That is not the case on all systems.

and int is 4 bytes.

It can be on some systems. That is not the case on all systems.

So sizeof(SizeTest) supposed to be 36 bytes

No. The size of a class is not "supposed" to be the sum of the size of its members.

Upvotes: 3

Related Questions