0

In the following code (on a 32 bit machine), if I print out the sizeof the pair, should I get 12? In my compiler I got 16. Is this always the case or it is compiler specific?

pair<int,string> b = std::make_pair(1,"randomcrap");
string c= "randomcrap";
cout << sizeof(c) << endl; //got 8 which make sense
cout << sizeof(b) << endl; //got 16
  • 1
    All compilers have padding so that the fields in a struct or class align to word boundaries. You can remove the padding with a compiler option and then it might be 12. – Jerry Jeremiah Sep 18 '18 at 01:53
  • `sizeof c` is going to be implementation-dependent. – jamesdlin Sep 18 '18 at 01:55
  • Actually I think it is supposed to be 16 for some compilers. An int is 4, but how large do you thing a string is? With g++ it's 12. A g++ std::string has a pointer to the heap, an int for the current size of the string and an int for the actual allocated capacity. That makes size() be O(n) but takes an extra 4 bytes. But it differs by compiler. See https://stackoverflow.com/questions/34560502/why-is-sizeofstdstring-only-eight-bytes – Jerry Jeremiah Sep 18 '18 at 02:00
  • In your case it is definitely padding because your std::string is only 8... – Jerry Jeremiah Sep 18 '18 at 02:02
  • 1
    By `string` do you mean `std::string` or something else? I don't see how `std::string` can have a size of only 8 – M.M Sep 18 '18 at 02:42

0 Answers0