In the C++ Standard Library, std::string
has a public member function capacity()
which returns the size of the internal allocated storage, a value greater than or equal to the number of characters in the string (according to here). What can this value be used for? Does it have something to do with custom allocators?
The capacity of a string reflects how much memory the string allocated to hold its contents. This value is measured in string characters, excluding the NULL terminator. For example, a string with capacity 8 could hold 8 characters. Returns the number of characters a string can hold without reallocation.
By default, a string buffer has a 16 character capacity.
Strings: The C-String and the string class. Recall that C++ supports two types of strings: The C-style string (or C-String) in header cstring (ported over from C's string. h ), which represents a string as a char array terminated by a null character '\0' (or 0) (null-terminated char array).
The C++ String class has length() and size() function. These can be used to get the length of a string type object. To get the length of the traditional C like strings, we can use the strlen() function. That is present under the cstring header file.
You are more likely to use the reserve()
member function, which sets the capacity to at least the supplied value.
The capacity()
member function itself might be used to avoid allocating memory. For instance, you could recycle used strings through a pool, and put each one in a different size bucket based on its capacity. A client of the pool could then ask for a string that already has some minimum capacity.
The string::capacity()
function return the number of total characters the std::string
may contain before it has to reallocate memory, which is quite an expensive operation.
A std::vector
works in the same way so I suggest you look up std::vector
here for an in detail explanation of the difference between allocated and initialized memory.
Update
Hmm I can see I misread the question, actually I think I've never used capacity() myself on either std::string or std::vector, seems to seldomely be of any reason as you have to call reserve anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With