gpt4 book ai didi

c++ - std::basic_string<_CharT> 字符串的最大长度

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:00:51 31 4
gpt4 key购买 nike

我想知道如何为给定平台确定字符串长度的上限(在 C++ 中)。

我仔细研究了很多库,其中大多数都是随意定义的。 GNU C++ STL(具有实验性 C++0x 特性的那个)有一个非常明确的定义:

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.

特别注意最后一行,“此外,此实现将此数量四分之一。”我认为这意味着除以四实际上完全是任意的.

我试图在 checkin log for basic_string.h 中找到更多信息,但它只能追溯到 2000 年 10 月 5 日,并且如该修订版所示,此注释已经存在,而且我对该代码库不够熟悉,无法知道该文件在它被删除之前可能位于源代码树中的什么位置移动到当前位置。

关于c++ - std::basic_string<_CharT> 字符串的最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2479459/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com