Size of a string

I notice that sizeof(string) always gives the value 28 (at least, in my laptop). However, when I declare a string with 100 characters, sizeof(str) still gives the value 28. Why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>
#include <string>

using namespace std;

int main()
{


	string st;
	for (int i = 1; i <= 100; i++)
		st += 'a';
	cout << st.length() << endl << sizeof(st);
	std::cin.get();
	return 0;
}
sizeof returns the size in bytes of its operand. sizeof(string) shouldn't change no matter what you name it although I have no idea how your getting 28, it should be 8 at least on a 64 bit machine.

I think your wanting the size of your string and not the variable.
Both string::size and string::length are synonyms and return the exact same value.
Try
cout << st.size();
or
cout << st.length();

Last edited on
sizeof gives you the size of all member variables of the string class (+ padding, and some other stuff). The string class contains at least one pointer. The size of the thing that the pointer points to is not included in the sizeof value, only the size of the pointer is.

Exactly what size you get depends on how the string class is implemented. You might also get a different size if you compile the program in release mode.
Last edited on
sizeof(std::string), in-object space for small string storage:

GNU libstdc++ (conforming implementation, GCC 5.2 or later): 32, 15
LLVM libc++: 24, 22
Microsoft msc++ 19.00 (VS 2015): 28, 15

The Microsoft implementation sizeof(std::string) == 28 is extremely simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// TEMPLATE CLASS _String_val
template<class _Val_types>
	class _String_val : public _Container_base
	{	// base class for basic_string to hold data

	    // ...

        enum
            {	// length of internal buffer, [1, 16]
                _BUF_SIZE = 16 / sizeof (value_type) < 1 ? 1
                    : 16 / sizeof (value_type)};

        union _Bxty
            {	// storage for small buffer or pointer to larger one
                value_type _Buf[_BUF_SIZE];
                pointer _Ptr;
                char _Alias[_BUF_SIZE];	// to permit aliasing
            } _Bx;

        size_type _Mysize;	// current length of string
	size_type _Myres;	// current storage reserved for string

        value_type *_Myptr()
            {	// determine current pointer to buffer for mutable string
                return (this->_BUF_SIZE <= this->_Myres // not a small string? (comment added) 
                    ? _STD addressof(*this->_Bx._Ptr)
                    : this->_Bx._Buf);
            }

            // ...
	}
// ... 
Last edited on
Topic archived. No new replies allowed.