我想知道如何确定给定平台的字符串(C++ 中)长度的上限。
我仔细检查了很多库,其中大多数都是任意定义的。 GNU C++ STL(具有实验性 C++0x 功能的 STL)有一个相当明确的定义:
size_t npos = size_t(-1); /*!< The maximum value that can be stored in a variable of type size_t */
size_t _S_max_len = ((npos - sizeof(_Rep_base))/sizeof(_CharT) - 1) / 4; /*!< Where _CharT is a template parameter; _Rep_base is a structure which encapsulates the allocated memory */
我是这样理解这个公式的:
- size_t 类型必须保存分配给字符串的单元数(其中每个单元的类型为 _CharT)
- 理论上,size_t类型的变量可以取的最大值是可以分配的1字节(即char类型)单元的总数
- 因此,前一个值减去跟踪分配的内存 (_Rep_base) 所需的开销就是字符串中的最大单元数。将此值除以 sizeof(_CharT),因为 _CharT 可能需要多个字节
- 从先前的值中减去 1 以考虑终止字符
- 最后,除法除以 4。我完全不知道为什么!
我查了很多地方寻求解释,但都找不到令人满意的解释(这就是为什么我一直在试图弥补一些东西!如果我错了,请纠正我!!)。
GCC 4.3.4 中的 basic_string.h 中的注释指出:
// 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.
特别注意最后一行,“此外,本次实施将这一金额分为四等分。”我认为这意味着除以四实际上是完全任意的.
我试图在以下位置找到更多信息basic_string.h 的签入日志,但它只能追溯到 2000 年 10 月 5 日,并且该注释已经存在,如该修订版中所示,并且我对该代码库不够熟悉,无法知道该文件在发布之前可能位于源代码树中的位置移动到当前位置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)