Default capacity of std::string?

2019-01-27 21:29发布

问题:

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;

回答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.



回答2:

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.



回答3:

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.



回答4:

It depends on the compiler. Take a look here, there is a good explanation:

http://www.learncpp.com/cpp-tutorial/17-3-stdstring-length-and-capacity/



回答5:

Generally, yes they allocate memory on the heap. I'll give an example: c_str() requires a NULL trailing character '\0'. Most implementations allocate this NUL \0 ahead of time, as part of the string. So you'll get at least one byte allocated, often more.

If you really need specific behavior I'd advise writing your own class. Buffer/string classes are not that hard to write.