Search code examples
c++stringstluse-casecapacity

When do we need to call std::string::capacity()?


As a user, I have std::string's size()/resize()/reserve() to know and manage the memory of all these strings.

But, when do I have to use capacity()? Is there any use case or necessity that I should call this function to do something to achieve something?

Thanks!


Solution

  • It's a good question. I'm going to run a risk of a flame war by saying that the calling of capacity() in user code is a code smell.

    The only reason to call it would be to avoid a memory allocation mid-operation. In which case, a cleaner and more fault-tolerant strategy would be to create one's own class (say limited_length_string). A possible implementation might allocate sufficient memory up front (either through it's own implementation or by encapsulating a std::string and calling reserve() on it.

    If you see this call in code you're working on, then beware of landmines. If you write this call, it's a signal that your design is suspect.