max_size 定义了该容器在理论上可以针对该容器的特定实现具有的最大大小。
该数字不取决于操作系统或可用内存,而仅由容器的实现给出。
如果你的(不兼容std::string)字符串容器的实现是这样的:
struct string {
unsigned char size;
char *data;
// … further functions …
};
那么max_size 可能是指unsigned char 可以代表的最大数字。
如果您的实现只是一个\0 终止的字符串,没有任何其他元信息。那么max_size 可能是指对于给定的目标架构,可以通过指针寻址的最大字节数。
所以max_size 只是说,容器的实现方式将能够处理max_size 个元素。但这并不能保证操作系统能够做到这一点。
对于std::string,实现可以处理的最大字符数的上限由size_type 的最大数量和一些进一步的限制给出。
std::string 的 size_type 本身由使用的分配器 (std::allocator<CharT>) 给出,默认为 std::allocator_traits<Allocator>::size_type。
对于std::allocatorsize_type 的推荐人std::size_t。
所以对于std::string,max_size 的上限是std::size_t 的最大值减去满足字符串其他要求所需的值n。
gcc-4.6.2 的libstdc++ 定义了says this 关于max_size:
// The maximum number of individual char_type elements of an
// individual string is determined by _S_max_size. This is the
// value that will be returned by max_size(). (Whereas npos
// is the maximum number of bytes the allocator can allocate.)
// If one was to divvy up the theoretical largest size string,
// with a terminating character and m _CharT elements, it'd
// look like this:
// npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT)
// Solving for m:
// m = ((npos - sizeof(_Rep))/sizeof(CharT)) - 1
// In addition, this implementation quarters this amount.
static const size_type _S_max_size;
static const _CharT _S_terminal;
以及对应的initialization
template<typename _CharT, typename _Traits, typename _Alloc>
const typename basic_string<_CharT, _Traits, _Alloc>::size_type
basic_string<_CharT, _Traits, _Alloc>::
_Rep::_S_max_size = (((npos - sizeof(_Rep_base))/sizeof(_CharT)) - 1) / 4;
根据这个197. max_size() underspecified(不确定是否有任何更新),max_size 的值不会因调用而改变:
LWG 很清楚,max_size() 返回的值不能随调用而改变。
因此您可以使用eerorika 的方法来获取特定分配器的值。