why is string storage 28 instead of 24

62 Views Asked by At

I've been trying to learn more about storage stuff using c++. I knew that they are store in the stack therefore the order was the contrary. However, why when i want to get the reference of the string, it shows me that the storage for that is about 28 instead of 24 since 56-28=28.

here is my code:

    #include <iostream>
    int main(){
    std::string name = "name";
    int age = 18;
    std::string last = "lastname";






    std::cout << &name << "\n"; //140701916868960
    std::cout << &age << "\n"; //140701916868956
    std::cout << &last << "\n"; //140701916868928
    }
1

There are 1 best solutions below

0
Igor Levicki On
  • You can't deduce the storage size of C++ objects like std::string by doing simple pointer arithmetic.
  • Default packing for 64-bit programs is 8 bytes which means that any object stored will be aligned to 8-byte boundary.
  • C standard doesn't mention stack at all, and there is no guarantee that variables will be stored in the same order as they are defined.