std::string
is a class that is part of the standard library, used to hold a string. It manages the allocation/deallocation of the dynamic memory for the string, and contains data members for the pointer to the memory, its size, and possible others.
sizeof(std::string)
returns the size of the std::string
object, not that of the actual string. It depends on the implementation of the standard library and is not fixed by the C++ standard. On that particular implementation it is 24 bytes.
An array of std::string
objects logically has a total size which is a multiple of sizeof(std::string)
, because arrays are always multiple instances of the object concatenated in memory.
To get the length of the actual string, use str.length()
, where str
is the std::string
object. The actual allocated memory size is always at least 1 byte more, because str.c_str()
will return a pointer to the string, with a terminating NULL byte at the end of it. The class allocates and deallocates memory as needed when the string is changed, and may internally allocate more memory than is needed by the string's size.
Theoretically, the std::string
class could also have been implemented so that it is smaller than 24 bytes (for example, if it contained just a pointer and an integer for the length). One reason it is that way is because the standard library implementation does small string optimization, i.e. if the string is short (less than 24 characters), it will be put into the std::string
object itself, and it will allocate no dynamic memory for it. So there also needs to be a flag inside the std::string
that indicates this.
Also, a string literal in C++ will not be of type std::string
, but it will be a raw C-string of type char[N]
. So sizeof("test")
returns 5
, because it is a char[5]
. (4 bytes for the characters, plus one additional 0 byte at the end.)