Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses for the capacity value of a string

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?

like image 524
dreamlax Avatar asked May 21 '10 11:05

dreamlax


People also ask

What is capacity of a string?

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.

What is default capacity of string?

By default, a string buffer has a 16 character capacity.

Does C++ have a string?

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).

How do you find the length of a string in C++?

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.


2 Answers

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.

like image 75
Marcelo Cantos Avatar answered Sep 28 '22 05:09

Marcelo Cantos


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.

like image 35
Viktor Sehr Avatar answered Sep 28 '22 06:09

Viktor Sehr