Default capacity of std::string?

10,887

Solution 1

Unfortunately, the answer is no according to N3290.

Table 63 Page 643 says:

  • data() a non-null pointer that is copyable and can have 0 added to it
  • size() 0
  • capacity() an unspecified value

The table is identical for C++03.

Solution 2

No, but, and I don't know of any implementation that does allocate memory on the heap by default. Quite a few do, however, include what's called the short string optimization (SSO), where they allocate some space as part of the string object itself, so as long as you don't need more than that length (seems to be between 10 and 20 characters as a rule) it can avoid doing a separate heap allocation at all.

That's not standardized either though.

Solution 3

It is implementation dependent. Some string implementations use a small amount of automatically allocated storage for small strings, and then dynamically allocate more for larger strings.

Share:
10,887
void.pointer
Author by

void.pointer

Updated on June 04, 2022

Comments

  • void.pointer
    void.pointer almost 2 years

    When I create a std::string using the default constructor, is ANY memory allocated on the heap? I'm hoping the answer does not depend on the implementation and is standardized. Consider the following:

    std::string myString;
    
  • Spire
    Spire about 12 years
    Nitpick: The "null" in "null terminator" refers to an ASCII NUL character, which is spelled differently from the null pointer NULL.
  • visitor
    visitor about 12 years
    In VC++ this should be covered by the small string optimization. G++ uses ref-counting: all empty strings are represented by the same statically allocated piece of memory. Which implementations actually do involve a dynamic allocation for empty strings?
  • velkyel
    velkyel over 4 years
    that is not literally ref-counting. References to this memory with '\0' are not counted at all.