6

Why isn't max_size a static member of std::string?

This compiles but I think its strange that a property common to all strings can only be accessed via an instance of a string:

std::size_t max_size = std::string().max_size();

Why is it implemented like this?

Baz
  • 12,713
  • 38
  • 145
  • 268
  • Maybe a duplicate of [Why isn't std::string::max_size a compile-time constant?](http://stackoverflow.com/questions/13137766/why-isnt-stdstringmax-size-a-compile-time-constant) – Mickaël Le Baillif Nov 28 '12 at 10:46

1 Answers1

7

Why isn't max_size a static member of std::string?

Because max_size return value depends on the allocator instance that the string instance uses internally.

utnapistim
  • 26,809
  • 3
  • 46
  • 82
  • Is it possible to have a std::vector of strings where the max_size is not the same for each instance in the vector? If so, how would one write an algorithm to find the shortest string in the vector? Such an algorithm would begin with the line std::size_t shortest_size = std::string().max_size(); Before iterating over the vector to update the value of shortest_size. – Baz Nov 28 '12 at 10:50
  • 1
    It *may* depends on the allocator, but it seems that it does not. According to the [`std::string` documentation](http://www.cplusplus.com/reference/string/string/string/) : "[...]under no known compiler implementation the memory allocation model for strings (`allocator`) is affected by its value[...]" – Mickaël Le Baillif Nov 28 '12 at 10:51
  • @MickaëlLeBaillif - as far as I understand, this is true for `std::string` (as it is defined in terms of `std::allocator`). Consider that one could define a LoonyLoopyAllocator and `typedef std::basic_string,LoonyLoopyAllocator> LoonyLoopyString;`. In that case, max_size() will no longer offer the same guarantee. – utnapistim Nov 28 '12 at 12:17
  • @Baz, if I understand you correctly, the shortest string should be determined using `std::string::size()`, not `max_size()`. – utnapistim Nov 28 '12 at 12:25