sizeof(string)

The execution of:

sizeof(string);

returns 32 on my machine. What do these 32 bytes contain? If I had to guess, I'd say there'd be:

1. A pointer to the first character (4 bytes?)
2. A long member representing the allocated capacity (4 bytes?)
3. A long member representing the size of the string (4 bytes?)
4. ... ?

Am I on the right track, or am I lost? If we didn't have such a great forum, how would one find out the answer to this question? I had a quick look in the C++ standards doc and didn't find much on it...
returns 32 on my machine. What do these 32 bytes contain?


- It's implementation dependent.

- It doesn't really matter as long as string operates as you expect it to

- You can examine <string> yourself and find out if you really want to know.

- There's probably more going on behind the scenes than you might think. Reference couting comes to mind


EDIT: I just realized my post is kind of a jerk response and not very helpful. Sorry.

Basically I don't know and I don't see any reason why it would matter.
Last edited on
All good. I totally agree that it doesn't matter. Even still, I'm sure you'd agree that one is surely allowed to be curious about such things.

Upon further investigation I learnt a few things, like how amazingly in-depth some of these standard header files are. This is going to make me sound like a real newbie, but I actually thought that there was ONLY ONE <string> header file. I soon found out that there's different implementations done by heaps of companies like Microsoft, Silicon Graphics etc (that's right, yeah?).

You also introduced me to yet another new concept: reference counting. I have no idea what that is, and now I'm gonna go away and check that out too.

So yeah, even though I still don't know what those 32 bytes are used for, your response was more helpful that you thought. Cheers.
A std::string is a class, so it is (as Disch said) implementation dependant. There are only very rare circumstances where you need to know the sizeof a class or class object.

As for reference counting: it is a way to keep memory usage to a minimum.
http://en.wikipedia.org/wiki/Reference_counting

The reference counting used by the string class is not for garbage collection, but for copy on write optimization.
http://en.wikipedia.org/wiki/Copy_on_write

Hope this helps.
Topic archived. No new replies allowed.