sizeof
returns the size of an expression. For you, that's a std::string
and for your implementation of std::string
, that's four. (Probably a pointer to the buffer, internally.)
But you see, that buffer is only pointed to by the string, it has no effect on the size of the std::string
itself. You want message.size()
for that, which gives you the size of the string being pointed to by that buffer pointer.
As the string
's contents change, what that buffer pointer points to changes, but the pointer itself is always the same size.
Consider the following:
struct foo
{
int bar;
};
At this point, sizeof(foo)
is known; it's a compile-time constant. It's the size of an int
along with any additional padding the compiler might add.
You can let bar
take on any value you want, and the size stays the same because what bar
's value is has nothing to do with the type and size of bar
itself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…